问题描述
为需要定义为C函数的函数,为什么不应该指定 externC
?如果对C编译器没有影响,那么对编译器在编译C源文件时会产生什么影响?
在下面的头文件中删除 #ifdef __cplusplus
检查?
externC{
int MyFunc();
}
说需要 #ifdef
,但我不明白为什么:
构造 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:
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?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!