ubuntu - 试图包含一个库,但不断收到 'undefined reference to' 消息

我正在尝试使用 libtommath 库。我在 Ubuntu linux 上为我的项目使用 NetBeans IDE。我已经下载并构建了库,我已经完成了“make install”,将生成的 .a 文件放入/usr/lib/并将 .h 文件放入/usr/include

它似乎正确地找到了文件(因为我不再收到这些错误,这是我在安装到/usr 目录之前所做的)。

但是,当我创建一个简单的 main 调用 mp_init(在库中)时,当我尝试创建我的项目时出现以下错误:

mkdir -p build/Debug/GNU-Linux-x86
rm -f build/Debug/GNU-Linux-x86/main.o.d
gcc -c -g -MMD -MP -MF build/Debug/GNU-Linux-x86/main.o.d -o build/Debug/GNU-Linux-x86/main.o main.c
mkdir -p dist/Debug/GNU-Linux-x86
gcc -o dist/Debug/GNU-Linux-x86/cproj1 build/Debug/GNU-Linux-x86/main.o
build/Debug/GNU-Linux-x86/main.o: In function 'main':
/home/[[myusername]]/NetBeansProjects/CProj1/main.c:18: undefined reference to `mp_init'
collect2: ld returned 1 exit status
make[2]: *** [dist/Debug/GNU-Linux-x86/cproj1] Error 1

所以,看起来链接器在库中找不到函数,但它就在那里,所以我只是不知道是什么原因造成的。

如果我直接输入 gcc 命令并跳过 makefile,我会得到同样的错误,我还确保静态库也使用 gcc 编译。

编辑添加:

如果我直接编译并使用 -l 或 -L 添加库,我会得到同样的错误:

$ gcc -l /usr/lib/libtommath.a main.c 
/usr/bin/ld: cannot find -l/usr/lib/libtommath.a
collect2: ld returned 1 exit status

$ gcc -llibtommath.a main.c 
/usr/bin/ld: cannot find -llibtommath.a
collect2: ld returned 1 exit status

$ gcc -Llibtommath.a main.c 
/tmp/ccOxzclw.o: In function `main':
main.c:(.text+0x18): undefined reference to `mp_init'
collect2: ld returned 1 exit status

$ gcc -Llibtommath.a main.c 
/tmp/ccOxzclw.o: In function `main':
main.c:(.text+0x18): undefined reference to `mp_init'
collect2: ld returned 1 exit status

我对这些东西很生疏,所以我不确定我在这里使用了正确的命令,在 -L 示例中是否找到了库?如果找不到图书馆,我到底如何才能找到图书馆?它在/usr/lib 中,我已经尝试使用当前目录中的 .a 文件等。是否需要设置环境变量?如果是,如何,等等。

我尝试了一个完全不同的库 (GMP) 并遇到了完全相同的问题。这一定是某种 Ubuntu 环境问题?有人知道如何解决这个问题吗?

最佳答案

这里的技巧是把库放在你正在编译的模块之后。问题是引用的东西。链接器按顺序解析引用,因此当库在模块被编译之前,链接器会感到困惑并且认为不需要库中的任何函数。通过将库放在模块之后,模块中对库的引用由链接器解析。

关于ubuntu - 试图包含一个库,但不断收到 'undefined reference to' 消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1517138/

相关文章:

javascript - 我可以使用 webpack 分别生成 CSS 和 JS 吗?

android - 如何将构建时间戳写入apk

python - 有没有办法将 python 应用程序编译成静态二进制文件?

android - 使用 gradle 签署产品 flavor

build - CMakeLists.txt 中未使用 CMAKE_BUILD_TYPE

c++ - 从父 CMakeLists.txt 覆盖 CMake 中的默认选项(...)值

visual-studio - Visual Studio 在构建期间不断挂起

ios - Swift 框架不适用于命名为 'Debug' 或 'Release' : No suc

visual-studio-2010 - MSbuild 是否需要在构建服务器上安装 Visual

c# - 自动在 Visual Studio c# 项目中嵌入 mercurial 修订信息