簡體   English   中英

為什么我會收到 linker 錯誤:未定義對...的引用?

[英]Why am I getting a linker error: undefined reference to …?

為什么我會收到此錯誤: undefined reference to `bfopen(char const*, int)'

我有一個我創建的共享庫,其中包括 function bfopen等的 function 定義。 這個庫的名稱是libfiles.so ,它位於我正在構建的本地ext/lib目錄中。

我正在編譯:

g++ -std=c++11 -fPIC -g -Wall -D_DEBUG -I$(PWD)/src -I$(PWD)/ext/include -o parser_tst parser_tst.cc $(PWD)/src/parser.o -L$(PWD)/ext/lib -lpthread -lfftw3f -ldsp -lfiles

我已經用$(PWD)代替了我的工作目錄。 我用nm -D ext/lib/libfiles.so libfiles.so libfiles.so 內部,並且能夠找到其中列出的 function 定義,所以我不知所措。 我也沒有收到任何錯誤,例如file does not exist: libfiles.so ,所以看起來它至少與該文件鏈接。

這是我的設置示例:(所有路徑都被剪裁到它們的本地路徑)

分機/樣本/src/test.h:

#ifndef TEST_H
#define TEST_H

int test();

#endif /* TEST_H */

ext/sample/src/test.c:

#include "test.h"

int test() {
    return 0;
}

這是清理后的文件結構:

.
./ext
./ext/Makefile
./ext/sample
./ext/sample/src
./ext/sample/src/Makefile
./ext/sample/src/test.c
./ext/sample/src/test.h
./ext/sample/tst
./ext/sample/tst/Makefile
./ext/sample/Makefile
./ext/sample/ext
./src
./tst
./tst/test_tst.cc
./tst/Makefile
./Makefile

調用make build后,它看起來像這樣:

.
./ext
./ext/Makefile
./ext/sample
./ext/sample/src
./ext/sample/src/Makefile
./ext/sample/src/test.c
./ext/sample/src/test.h
./ext/sample/src/test.o
./ext/sample/tst
./ext/sample/tst/Makefile
./ext/sample/Makefile
./ext/sample/ext
./ext/sample/include
./ext/sample/include/test.h
./ext/sample/lib
./ext/sample/lib/libtest.so
./ext/lib
./ext/lib/libtest.so
./ext/include
./ext/include/test.h
./src
./tst
./tst/test_tst.cc
./tst/Makefile
./Makefile

最后我調用make test產生 output (包括錯誤):

make  -i -C ./tst
make[1]: Entering directory `$(PWD)/tst'
make all_tst
make[2]: Entering directory `$(PWD)/tst'
g++ -std=c++11 -fPIC -g -Wall -D_DEBUG -I./src -I$(PWD)/ext/include -o test_tst test_tst.cc -L$(PWD)/ext/lib -ltest
test_tst.cc: In function ‘int main(int, char**)’:
test_tst.cc:4:6: warning: unused variable ‘t’ [-Wunused-variable]
  int t = test();
      ^
/tmp/ccMq869q.o: In function `main':
$(PWD)/tst/test_tst.cc:4: undefined reference to `test()'
collect2: error: ld returned 1 exit status
make[2]: [test_tst] Error 1 (ignored)
make[2]: Leaving directory `$(PWD)/tst'
make[1]: Leaving directory `$(PWD)/tst'

我嘗試使用與export ( setenv LD_LIBRARY_PATH. ) 等效的 tcsh ,但這沒有幫助

一個可能的問題是,您有一個ext/sample/src/test.c一個 C 文件,它將被編譯為 C 代碼。

但是您使用您的庫的應用程序是 C++ 代碼

g++ -std=c++11 -fPIC -g -Wall -D_DEBUG -I./src -I$(PWD)/ext/include -o test_tst test_tst.cc -L$(PWD)/ext/lib -ltest

並包括一個 header,在這種情況下,它也從 c++ 文件編譯為 C++ 代碼,但從您的 C 文件編譯為 C 代碼!

因此,您應該將 c++ 代碼中的 header 包含在:

extern "C" {
#include "test.h"
}

如何混合 C 和 C++ 代碼:混合 C 和 ZF6F87C9FDCF8B3712F07F93F1 代碼

linker 無法從 c 文件中找到該符號的原因是,名稱在 C++ 中被“分解”,因為它需要一個“技巧”來執行 ZC1C425268E68385D1AB5074C17Z 重載9。 可以在這里找到更好和更詳細的解釋: name mangling

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM