sha*_*anu 3 c c++ linker makefile
#include "abc.h"
int abc()
{
return 10;
}
Run Code Online (Sandbox Code Playgroud)
int abc();
Run Code Online (Sandbox Code Playgroud)
#include "abc.h"
int main()
{
abc();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
CC=gcc -O2
CP=g++
mymain: mymain.o abc.o
$(CP) -o mymain mymain.o abc.o
mymain.o: mymain.cpp abc.h
$(CP) -c mymain.cpp abc.h
abc.o: abc.c abc.h
$(CC) -c abc.c abc.h
clean:
$(RM) *.o mymain
Run Code Online (Sandbox Code Playgroud)
g++ -c mymain.cpp abc.h
gcc -O2 -c abc.c abc.h
g++ -o mymain mymain.o abc.o
mymain.o: In function `main':
mymain.cpp:(.text+0x5): undefined reference to `abc()'
collect2: error: ld returned 1 exit status
make: *** [mymain] Error 1
Run Code Online (Sandbox Code Playgroud)
为什么abc()是未定义的引用?
extern "C" {
int abc();
}
Run Code Online (Sandbox Code Playgroud)
g++ -c mymain.cpp abc.h
gcc -O2 -c abc.c abc.h
In file included from abc.c:1:0:
abc.h:1:8: error: expected identifier or ‘(’ before string constant
extern "C" {
^
abc.h:1:8: error: expected identifier or ‘(’ before string constant
extern "C" {
^
make: *** [abc.o] Error 1
Run Code Online (Sandbox Code Playgroud)
问题是你试图将C函数链接到C++对象,而不告诉编译器这是你正在做的事情.
如果您的头文件(abc.h)看起来像这样:
extern "C" {
int abc();
}
Run Code Online (Sandbox Code Playgroud)
它会工作(当包含在C++源代码中......但是当它包含在C源代码中时会中断).
你可以将它extern "C" {和它的尾部括}在宏中,如结合C++和C所示 - #ifdef __cplusplus如何工作?为了适合C和C++包含.
请注意,$(CP) -c mymain.cpp abc.h在makefile中没有意义 - 您不希望在编译器命令行上指定标头.这适用于该模式的两个实例.