我们可以使用外部“C”在C文件没有#ifdef __cplusplus? [英] Could we use extern "C" in C file without #ifdef __cplusplus?
问题描述
为需要定义为C函数的函数,为什么不应该指定 externC
?如果对C编译器没有影响,那么对编译器在编译C源文件时会产生什么影响?
在下面的头文件中删除 #ifdef __cplusplus
检查?
externC{
int MyFunc();
}
对另一个问题的回答说需要 #ifdef
,但我不明白为什么:
关于#2:将为通过C ++编译器运行的任何编译单元定义__cplusplus。通常,这意味着.cpp文件和该.cpp文件包括的任何文件。相同的.h(或.hh或.hpp或what-have-you)在不同的时间可以解释为C或C ++,如果不同的编译单元包括它们。如果你希望.h文件中的原型引用C符号名,那么当它们被解释为C ++时,它们必须具有
externC
,并且它们不应该具有externC
当解释为C - 因此#ifdef __cplusplus
检查。
构造 externC
是一个C ++构造,不被C编译器识别。通常,它会发出一个语法错误消息。
一个常见的技巧是定义一个宏,例如EXTERN_C,扩展到不同的东西取决于你是否编译使用C或C ++。例如:
在一个公共头文件中:
#ifdef __cplusplus
#define EXTERN_C externC{
#define EXTERN_C_END}
#else
#define EXTERN_C
#define EXTERN_C_END
#endif $ b $ <$> c $ c> EXTERN_C
int MyFunc(void);
EXTERN_C_END
Why shouldn’t extern "C"
be specified for a function that needs to be defined as a C function? What effect would that have on the compiler when compiling the file as a C source?
If there is no effect on the C compiler, can’t we just define a function in a header file as below by removing the #ifdef __cplusplus
check?
extern "C" {
int MyFunc();
}
An answer to another question says that the #ifdef
is needed, but I don’t understand why:
Regarding #2: __cplusplus will be defined for any compilation unit that is being run through the C++ compiler. Generally, that means .cpp files and any files being included by that .cpp file. The same .h (or .hh or .hpp or what-have-you) could be interpreted as C or C++ at different times, if different compilation units include them. If you want the prototypes in the .h file to refer to C symbol names, then they must have
extern "C"
when being interpreted as C++, and they should not haveextern "C"
when being interpreted as C -- hence the#ifdef __cplusplus
checking.
The construct extern "C"
is a C++ construct and is not recognized by a C compiler. Typically, it will issue a syntax error message.
A common trick is to define a macro, for example EXTERN_C, that would expand to different thing depending on if you compile using C or C++. For example:
In a common header file:
#ifdef __cplusplus
#define EXTERN_C extern "C" {
#define EXTERN_C_END }
#else
#define EXTERN_C
#define EXTERN_C_END
#endif
In other files:
EXTERN_C
int MyFunc(void);
EXTERN_C_END
这篇关于我们可以使用外部“C”在C文件没有#ifdef __cplusplus?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!