将c代码链接到c ++代码时的g ++链接顺序依赖性

2022-01-11 00:00:00 c g++ linker c++

在今天之前,我一直认为对象和库在链接阶段传递给 g++ 的顺序并不重要.然后,今天,我尝试从 c++ 代码链接到 c 代码.我将所有 C 标头包装在一个外部C"块中,但链接器仍然难以找到我知道在 C 对象档案中的符号.

Prior to today I had always believed that the order that objects and libraries were passed to g++ during the linking stage was unimportant. Then, today, I tried to link from c++ code to c code. I wrapped all the C headers in an extern "C" block but the linker still had difficulties finding symbols which I knew were in the C object archives.

很困惑,我创建了一个相对简单的示例来隔离链接错误,但令我惊讶的是,更简单的示例链接没有任何问题.

Perplexed, I created a relatively simple example to isolate the linking error but much to my surprise, the simpler example linked without any problems.

经过一些尝试和错误,我发现通过模拟简单示例中使用的链接模式,我可以得到主代码链接OK.该模式首先是对象代码,其次是对象档案,例如:

After a little trial and error, I found that by emulating the linking pattern used in the simple example, I could get the main code to link OK. The pattern was object code first, object archives second eg:

g++ -o serverCpp serverCpp.o algoC.o libcrypto.a

谁能解释为什么会这样?我在链接普通c++代码时从未见过这个问题.

Can anyone shed some light on why this might be so?. I've never seen this problem when linking ordinary c++ code.

推荐答案

可以使用--start-group archives --end-group并编写 2 个依赖库而不是 archives:

You can use --start-group archives --end-group and write the 2 dependent libraries instead of archives:

gcc main.o -L. -Wl,--start-group -lobj_A -lobj_b -Wl,--end-group

相关文章