Why does the order of passing parameters to g++ matter

江枫思渺然 提交于 2021-02-07 14:00:33

问题


Recently, I was trying to build an application, which uses some libraries, available in form of shared object files. I wasted lot of time in compiling the CPP code and it didn't work.

Below is the command, previously I was trying to compile the code-

g++ -I/opt/ros/indigo/include/ -I/usr/include/eigen3/ -L/opt/ros/indigo/lib/ -lorocos-kdl -lkdl_parser test.cpp -o test

The above command always shows many undefined references errors. Just for the curiosity, I changed the order of parameters. Below is the command, which is working-

g++ -L/opt/ros/indigo/lib -I/opt/ros/indigo/include -I/usr/include/eigen3 test.cpp -lorocos-kdl -lkdl_parser -o test

I posted the complete code and solution here.

My question is why does the order of passing parameters to g++ matter? Is there any alternative to avoid such problems in future?


回答1:


Generally the order of arguments doesn't matter, but there are of course exceptions. For example if you provide multiple -O flags it will be the last one that is used, the same for other flags.

Libraries are a little different though, because for them the order is significant. If object file or library A depends on library B, then A must come before B on the command line. This is because of how the linker scans for symbols: When you use a library the linker will check if there are any symbols that could be resolved. Once this scan is over the library is discarded and will not be searched again.

This means when you have -lorocos-kdl -lkdl_parser test.cpp the linker will scan the libraries orocos-kdl and kdl_parser first, notice that there aren't dependencies on these library, no symbols from the libraries are needed, and continue with the object file generated by the source file.

When you change the order to test.cpp -lorocos-kdl -lkdl_parser the linker will be able to resolve the undefined symbols referenced by test.cpp when it comes to the libraries.




回答2:


You can (at least in some versions of gcc) use parenthesis around the libraries if you don't want to care about the order.

See:

Why does the order in which libraries are linked sometimes cause errors in GCC?

Specifically:

If a static library depends on another library, but the other library again depends on the former library, there is a cycle. You can resolve this by enclosing the cycling dependent libraries by -( and -), such as -( -la -lb -) (you may need to escape the parens, such as -( and -)). The linker then searches those enclosed lib multiple times to ensure cycling dependencies are resolved.



来源:https://stackoverflow.com/questions/40603575/why-does-the-order-of-passing-parameters-to-g-matter

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!