C ++与.o和.a文件链接之间的区别:行为不同,为什么? [英] C++ differ between Linking with .o and with .a file: different behavior, why?

查看:304
本文介绍了C ++与.o和.a文件链接之间的区别:行为不同,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望:

与.o文件的链接以及从.o文件存档的.a文件的链接应该没有区别.

linking with .o file, and linking with .a file archived from the .o file, should have no difference.

但事实并非如此.我有2个源文件,每个源文件都声明1class + 1静态object + 1函数,还有一个main.cpp调用了其中一个函数

But the fact is not. I have got 2 source files, each declaring 1class+1 static object+1 function, and a main.cpp that called one of the functions

$cat First.cpp
#include<stdio.h>
struct First{
  First(){printf("First\n");}
};
void f1(){printf("f1\n");}//Not called in main
static First f_obj;

$cat Second.cpp
#include<stdio.h>
struct Second{
  Second(){printf("Second\n");}
};
void f2(){printf("f2\n");}//Not called in main
static Second s_obj;

$cat main.cpp
void f2();
int main()
{
    f2();
    return 0;
}

$g++ -c First.cpp  -fPIC
$g++ -c Second.cpp -fPIC
$ar -rvs libmystatic.a  First.o Second.o
$g++ main.cpp -o MylinkSta -lmystatic -L.
$g++ main.cpp -o MyDirect First.o Second.o

$./MylinkSta
Second
f2

$./MyDirect
Second
First
f2

所以你可以看到

(1)MylinkSta的运行结果不是构造第一个"对象,而是MyDirect构造.

(1) The running result of MylinkSta doesn't construct 'First' object, but MyDirect does.

(2)始终构造第二"对象.

(2) While the 'Second' object is always constructed.

我真的看不到链接2个'.o'文件和链接从这2个'.o'文件中存档的'.a'文件之间的区别.

I really don't see any difference between linking with 2 '.o' files, and linking with '.a' file that's archived from these 2 '.o' files.

为什么他们的行为有所不同?我在rhel/ubuntu上进行了gcc/clang的实验,结果都相同.我想知道是否有任何C ++ ABI标准规定何时应该通过任何链接选项真正调用创建的静态/全局对象?

Why they behave differently? I experimented with gcc/clang on rhel/ubuntu, all show the same result. I wonder if there's any C++ ABI standard that says when a static/global object created should be really invoked, by any linking option?

这种区别是怎么产生的?

How does this difference come from?

推荐答案

这是由于静态库的语义所致.如果链接器包含在命令行中位于它之前的某个目标文件引用的符号,则链接器将仅包含来自静态库的文件(例如,main.cpp从Second引用f2,因此包含了它).您可以通过以下方式覆盖图书馆周围的行为

This is due to semantics of static libs. Linker will only include files from static library if it contains symbol that is referenced by some object file which precedes it in command line (e.g. main.cpp references f2 from Second so it's included). You can override this behavior with surrounding you library with

-Wl,--whole-archive -lmystatic -Wl,--no-whole-archive

但这不是标准.

这篇关于C ++与.o和.a文件链接之间的区别:行为不同,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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