我有一个简单的程序
#include <glib.h> int main(){ g_print("hallo\n"); }
并尝试在Ubuntu上embedded式系统(Odroid X2)上编译它
root@odroid:~/# gcc $(pkg-config --libs --cflags glib-2.0) -o main main.c /tmp/cci48ASK.o: In function `main': main.c:(.text+0xc): undefined reference to `g_print' collect2: error: ld returned 1 exit status
安装的编译器:
root@odroid:~/x# gcc -v Using built-in specs. COLLECT_GCC=gcc COLLECT_LTO_WRAPPER=/usr/lib/gcc/arm-linux-gnueabihf/4.7/lto-wrapper Target: arm-linux-gnueabihf Configured with: ../src/configure -v --with-pkgversion='Ubuntu/Linaro 4.7.3-1ubuntu1' --with-bugurl=file:///usr/share/doc/gcc-4.7/README.Bugs --enable-languages=c,c++,go,fortran,objc,obj-c++ --prefix=/usr --program-suffix=-4.7 --enable-shared --enable-linker-build-id --libexecdir=/usr/lib --without-included-gettext --enable-threads=posix --with-gxx-include-dir=/usr/include/c++/4.7 --libdir=/usr/lib --enable-nls --with-sysroot=/ --enable-clocale=gnu --enable-libstdcxx-debug --enable-libstdcxx-time=yes --enable-gnu-unique-object --disable-libitm --enable-plugin --with-system-zlib --enable-objc-gc --with-cloog --enable-cloog-backend=ppl --disable-cloog-version-check --disable-ppl-version-check --enable-multiarch --enable-multilib --disable-sjlj-exceptions --with-arch=armv7-a --with-fpu=vfpv3-d16 --with-float=hard --with-mode=thumb --disable-werror --enable-checking=release --build=arm-linux-gnueabihf --host=arm-linux-gnueabihf --target=arm-linux-gnueabihf Thread model: posix
任何想法,为什么链接器没有find参考?
gcc
(和其他编译器)的选项顺序很重要 。
gcc -Wall main.c $(pkg-config --libs --cflags glib-2.0) -o main
而我并不喜欢上述。 你应该学习如何使用GNU make 。 至少要把编译标志,源码,目标文件,库文件(从高级到低级)放在一起。
gcc -Wall $(pkg-config --cflags glib-2.0) main.c \ $(pkg-config --libs glib-2.0) -o main
更好的是,有一个Makefile
开始
CC=gcc CFLAGS= -Wall $(pkg-config --cflags glib-2.0) LIBES= $(pkg-config --libs glib-2.0)
并且应该避免编译为根。 只有安装应该需要root权限…
您可能想要添加-g
(用于调试信息的编译器标志)。 一旦程序准备就绪,几乎无bug,用-O2
(优化)替换它,然后再做一些严重的测试!
好的找到了解决方案
gcc -o main main.c `pkg-config --libs --cflags glib-2.0`
作品,但我不知道为什么在我的X64 Linux系统上,它的工作也是另一种方式。
您需要在编译行中添加$(pgk-config --libs glib-2.0)
到main.c
之后 – 因为如果有任何使用它们的函数,库函数只会被拖入二进制文件中,所以main.c就是使用g_print
,并且如果-lglib
(或者pkg-config
位的结果是)在main.c
之前,它不包含在生成的二进制文件中。