为什么要创建一个的.o某文件为静态链接? [英] Why create a .a file from .o for static linking?

查看:117
本文介绍了为什么要创建一个的.o某文件为静态链接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这个code:

one.c:

#include <stdio.h>

int one() {
   printf("one!\n");
   return 1;
}

two.c:

#include <stdio.h>

int two() {
   printf("two!\n");
   return 2;
}

prog.c中

prog.c

#include <stdio.h>

int one();
int two();

int main(int argc, char *argv[]) 
{
   one();
   two();

   return 0;
}

我想这些程序链接在一起。所以我这样做:

I want to link these programs together. So I do this:

gcc -c -o one.o one.c
gcc -c -o two.o two.c
gcc -o a.out prog.c one.o two.o

这工作就好了。

或者,我可以创造一个静态库:

Or I could create a static library:

ar rcs libone.a one.o
ar rcs libtwo.a two.o
gcc prog.c libone.a libtwo.a
gcc -L. prog.c -lone -ltwo

所以我的问题是:为什么我会使用第二个版本 - 而不是我的连接的.o文件 - 在我创建了一个。一个文件的人吗?他们都似乎是静态链接,所以有一个VS另一个好处或架构上的差异?

So my question is: why would I use the second version - the one where I created a ".a" files - rather than linking my ".o" files? They both seem to be statically linking, so is there an advantage or architectural difference in one vs another?

推荐答案

通常库是可以在多个程序中使用的目标文件的集合。

Typically libraries are collections of object files that can be used in multiple programs.

在您的例子没有什么优势,但你可能会做的:

In your example there is no advantage, but you might have done:

ar rcs liboneandtwo.a one.o two.o

然后连接你的程序变得更简单:

Then linking your program becomes simpler:

gcc -L. prog.c -loneandtwo

这的确包装的问题。你有一组目标文件自然地形成一套相关的功能,可以在多个程序中重用?如果是这样,那么他们可以理智地归档到一个静态库,否则有可能是没有任何优势。

It's really a matter of packaging. Do you have a set of object files that naturally form a set of related functionality that can be reused in multiple programs? If so, then they can sensibly be archived into a static library, otherwise there probably isn't any advantage.

有在链接的最后一步的重要区别之一。你链接的任何对象文件都将被包含在最终的方案。这是库的目标文件,如果他们帮助解决其它目标文件的任何未定义符号只包括在内。如果他们不这样做,他们就不会被链接到最终的可执行文件。

There is one important difference in the final link step. Any object files that you linked will be included in the final program. Object files that are in libraries are only included if they help resolve any undefined symbols in other object files. If they don't, they won't be linked into the final executable.

这篇关于为什么要创建一个的.o某文件为静态链接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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