我使用ar创建了一个静态库来创建一个简单的单词计数器,但是当我到达makefile中的链接阶段时,我收到以下错误:
g++ -o wordcount obj/word.o obj/main.o -Wall -L lib -llinkedlist
obj/word.o: In function `cleanUp(linkedList*)':
word.c:(.text+0x83): undefined reference to `ll_clear(linkedList*)'
obj/word.o: In function `initialize(linkedList*)':
word.c:(.text+0xa7): undefined reference to `ll_init(linkedList*)'
obj/word.o: In function `getTotalWordCount(linkedList*)':
word.c:(.text+0xbd): undefined reference to `ll_getIterator(linkedList*)'
word.c:(.text+0xd7): undefined reference to `ll_next(linkedListIterator*)'
word.c:(.text+0xea): undefined reference to `ll_hasNext(linkedListIterator*)'
obj/word.o: In function `getWord(linkedList*, unsigned int)':
word.c:(.text+0x118): undefined reference to `ll_get(linkedList*, unsigned int)'
obj/word.o: In function `findWord(linkedList*, char*)':
word.c:(.text+0x12e): undefined reference to `ll_getIterator(linkedList*)'
word.c:(.text+0x148): undefined reference to `ll_next(linkedListIterator*)'
word.c:(.text+0x178): undefined reference to `ll_hasNext(linkedListIterator*)'
obj/word.o: In function `combineCounts(linkedList*, wordData*)':
word.c:(.text+0x26e): undefined reference to `ll_add(linkedList*, void const*, unsigned int)'
obj/main.o: In function `main':
main.c:(.text+0x1df): undefined reference to `ll_getIterator(linkedList*)'
main.c:(.text+0x1f2): undefined reference to `ll_next(linkedListIterator*)'
main.c:(.text+0x25c): undefined reference to `ll_hasNext(linkedListIterator*)'
collect2: error: ld returned 1 exit status
makefile:38: recipe for target 'wordcount' failed
make: *** [wordcount] Error 1
但是,使用nm查看我的库的符号表会产生这些结果(为了便于阅读而被截断):
linkedlist.o:
00000028 T ll_add
00000124 T ll_addIndex
000003b7 T ll_clear
00000363 T ll_get
00000438 T ll_getIterator
00000477 T ll_hasNext
00000000 T ll_init
00000493 T ll_next
00000285 T ll_remove
00000420 T ll_size
我在类似问题中找到的所有答案都提到您指定库的顺序很重要,但我已经在我的所有其他目标文件之后添加了我的库。有没有人有任何想法我可能会出错?
答案 0 :(得分:0)
问题是该库是由C编译器编译的,但我编译了我的新源代码,用C ++编译器引用该库。这两种方法之间的目标文件输出是不同的。以下面的代码为例:
# Compile as C program
$ gcc -c main.c; nm main.o
00000000 T foo
00000018 T main
U printf
# Compile as C++ program
$ g++ -c main.c; nm main.o
00000018 T main
U printf
00000000 T _Z3fooi
将此文件作为C程序编译到目标文件中将产生与编译为C ++程序不同的符号。例如:
foo
正如您所见,{{1}}函数使用两个不同的符号编译。由于新的源文件是作为C ++编译的,因此链接器需要C ++样式符号,而库包含C样式符号。链接器无法与符号匹配,因此会抛出错误,因为C ++符号未定义。