将c代码链接到c ++代码时的g ++链接顺序依赖性 [英] g++ linking order dependency when linking c code to c++ code

查看:16
本文介绍了将c代码链接到c ++代码时的g ++链接顺序依赖性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在今天之前,我一直认为对象和库在链接阶段传递给 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

这篇关于将c代码链接到c ++代码时的g ++链接顺序依赖性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆