Question

I would like to include one header file in both C and C++, and I have a function defined in C code and few functions defined in external library.

#if defined(__cplusplus)
extern "C" {
#endif

void func0();

#if !defined(__cplusplus)
extern {
#endif

void func1();
int func2(int);

} /* extern */

This code produces compilation error when compiled from C source file

error C2059: syntax error : '{'

Is it possible to fix syntax error directly or I have to use some macros?

EXTERNCPP void func0();
EXTERNC void func1();
EXTERNC int func2(int);

Edit 1: I do not ask about Effects of the extern keyword on C functions, I just ask if it is possible to fix syntax in easy way. If it is not possible, i could still remove it completely for C part

Edit 2: To clarify what I want to get. If header is included

from C++:

extern "C" void func0(); 
extern "C" void func1(); 
extern "C" int func2(int);

from C:

void func0(); 
extern void func1(); 
extern int func2(int);
Was it helpful?

Solution 2

You can simply omit the extern { line when compiling as a C header.

OTHER TIPS

extern { is not needed.You need to remove it:-

#if defined(__cplusplus)
extern "C" {
#endif

void func0();

#if !defined(__cplusplus)

#endif

void func1();
int func2(int);

#if defined(__cplusplus)
}
#endif
#if defined(__cplusplus)
extern "C" {
void func0();
#endif

#if !defined(__cplusplus)
void func1();
int func2(int);
#endif

#if defined(__cplusplus)
}
#endif

* [EDIT] answering your last edit:

void func0(); /* included in both versions */

#if defined(__cplusplus)
extern "C" {
void func1(); 
int func2(int);
#endif

#if !defined(__cplusplus)
extern void func1(); 
extern int func2(int);
#endif

#if defined(__cplusplus)
}
#endif

If you want to use func0 as extern in C:

#if defined(__cplusplus)
extern "C" {
void func0();
void func1(); 
int func2(int);
#endif

/* C block */
#if !defined(__cplusplus)
extern void func0();
extern void func1(); 
extern int func2(int);
#endif

#if defined(__cplusplus)
}
#endif

If you don't want to use it at all (from C) remove it from the C block

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top