编译包含extern"C"的程序

jor*_*gen 9 c c++ header-files extern

我正在尝试使用makefile来编译其他人编写的程序,使用cygwin.我收到很多错误信息,其中很多都抱怨error: template with C linkage.

在搜索了一下后,似乎问题与之相关extern "C".该行包含在文件cygwin/usr/include/pthread.h中,该文件包含#include < pthread.h >在其中一个标题中.当我删除此行时,大多数错误消息都会消失.但是还有一些,有以​​下几种:

/usr/include/pthread.h:67:5: error: previous declaration of ‘int pthread_atfork(void (*  )(),void ( *)(), void ( *)())’ with ‘C++’ linkage

/usr/include/sys/unistd.h:136:5: error: conflicts with new declaration with ‘C’ linkage
Run Code Online (Sandbox Code Playgroud)

有谁知道如何解决这一问题?我很乐意坐下来详细了解所有这些东西,但我没有时间需要这个程序运行..

Zif*_*ion 11

编辑:根据评论中的交换,罪魁祸首是构建目录(Endian.h)中的头文件与系统包含文件/usr/include/endian.h冲突.它被包含在内而不是系统头,并导致构建问题.这些文件存在冲突,因为Windows上的案例无关紧要.根本原因是原始答案中的建议.extern C构造无意中泄漏到C++代码中,其中定义了模板,导致指示的错误.

我会检查你的头文件中的"悬空"C链接构造.这将是您编写的代码(不是任何系统头文件;这些可能是安全的).

标头中的代码包含在,

在上面:

#ifdef __cplusplus
extern "C" {
#endif
Run Code Online (Sandbox Code Playgroud)

在底部:

#ifdef __cplusplus
}
#endif
Run Code Online (Sandbox Code Playgroud)

如果缺少底部,则上半部分的效果会无意中延伸到其他标题中的代码中.这会导致您遇到的问题.


小智 8

当您的编译器正在编译C和C++代码的混合时,就会出现此问题.extern"C"语法是告诉C++编译器C编译器还需要访问此函数的一种方法.C编译器不理解extern的这种用法,所以通常你会隐藏它:



    #ifdef __cplusplus
    extern "C" {
    #endif
void whatever();
#ifdef __cplusplus } #endif
Run Code Online (Sandbox Code Playgroud)

但是,您不应该更改系统标题,那些错误的可能性非常小.更有可能你自己的一个标题缺少上面的右括号.