g++ 编译顺序问题

转自:https://blog.csdn.net/sunny04/article/details/17913949

https://cloud.tencent.com/developer/article/1178753

1.问题

g++ -lxxx main.cpp   -o main    //报错undefined reference to
g++  main.cpp -lxxx  -o main    //ok!

 即cpp文件要放到引用的库之前才行。

【大写L】-L:Add directory dir to the list of directories to be searched for -l.

【小写l】-l : Search the library named library when linking.

It makes a difference where in the command you write this option;
    the linker searches and processes libraries and object files in
    the order they are specified. Thus, `foo.o -lz bar.o' searches
    library `z' after file foo.o but before bar.o. If bar.o refers to
    functions in `z', those functions may not be loaded.

上面一段说的非常清楚, foo.o -lz bar.o这样的编译顺序,从左往右编译,在处理foo.o的时候,会查找右边的-l,能够找到z,然后在处理到bar.o的时候,右边没有依赖的库,如果它依赖了z,那么可能就会有找不到依赖的问题!

所以上面第一条命令,将库引用放在cpp之前,那么在处理到cpp的重定位时,向右边找就会找不到。。。

2.总结

在引用动态库时可以使用-L路径【大写】+-lxxx【小写】这种方式;

在引用静态库时直接-llibxxx.a【小写l】即可。

并且二者都要放在最后,,最好都放在最后,“被依赖的库需要放在后头”,引用规则如下:

g++ ...  obj($?) -l(上层逻辑lib) -l(中间封装lib) -l(基础lib) -l(系统lib)  -o $@

 

posted @ 2022-09-20 22:47  lypbendlf  阅读(91)  评论(0编辑  收藏  举报