c能编译的函数c++却不能编译
大神的链接:https://www.cnblogs.com/skynet/archive/2010/07/10/1774964.html
问题来源:编译简单的服务端程序,结果出现错误
$ g++ UNIX_TEXT.c -lunp
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x26):
undefined reference to `Socket(int, int, int)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x26):
relocation truncated to fit: R_X86_64_PC32 against undefined symbol
`Socket(int, int, int)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x98):
undefined reference to `Listen(int, int)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x98):
relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Listen(int, int)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0xbb):
undefined reference to `Accept(int, sockaddr*, int*)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0xbb):
relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Accept(int, sockaddr*, int*)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x110):
undefined reference to `Write(int, void*, unsigned long)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x110):
relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Write(int, void*, unsigned long)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x11d):
undefined reference to `Close(int)'
/tmp/cciCxwbF.o:UNIX_TEXT.c:(.text+0x11d):
relocation truncated to fit: R_X86_64_PC32 against undefined symbol `Close(int)'
collect2: error: ld returned 1 exit
status
同一个程序用g++编译就无法通过,但是用gcc却可以正常运行。
原因:c++允许函数重载,c不允许。所以两者的编译和链接规则不同。
解决方法:怎样实现混合编译,c++中使用c的函数;c中使用c++的函数
修改unp.h文件
开头:
1 #ifndef __unp_h 2 #define __unp_h 3 4 #ifdef __cplusplus 5 extern "C" 6 { 7 #endif
结尾:
1 #ifdef __cplusplus 2 } 3 #endif 4 5 #endif /* __unp_h */
上一篇: 合并两个有序数组(c++)
下一篇: 设计模式之组合模式(Composite)