g ++为什么不必须链接iostream二进制文件,而对于pthread却要这样做呢? [英] g++ why don't you have to link iostream binaries but for pthread you do?

查看:100
本文介绍了g ++为什么不必须链接iostream二进制文件,而对于pthread却要这样做呢?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果您有一个仅使用'cout'对象的非常基本的C ++程序,则可以在源文件中包含iostream,然后在进行编译时不必链接任何外部库.换句话说,您只需运行

If you have a very basic C++ program that only uses the 'cout' object, you can include iostream in the source file and then when you compile it you don't have to link any external libraries. In other words, you can simply run

g++ main.cpp -c

g++ main.o -o program

./program

当您要使用更复杂的对象(例如线程)时,不仅要包含pthread,而且在链接程序时必须链接到库.

When you want to use more complicated objects such as threads, not only do you include pthread, but when you link the program you have to link to a library.

g++ main.cpp -c

g++ main.o -lpthread -o program

./program

所以我的问题是,为什么我不必链接任何库才能使用所有iostream对象?

So my question is, why didn't I have to link any libraries to use all the iostream objects?

推荐答案

g++ main.o -o program链接时,您正在链接到库.默认情况下,一些库是自动链接的,链接到它们的唯一方法是传递-nodefaultlibs(或等效文件).特别是,您会在libstdc++中找到cout,而后者又使用libc.这两个默认情况下都是链接的.

You are linking to libraries when you link with g++ main.o -o program. A few libraries are auto-linked by default, and the only way to not link to them is to pass -nodefaultlibs (or equivalent). In particular, you'll find cout in libstdc++, which in turn uses libc. Both of those are linked by default.

如果已安装ldd,则可以通过运行ldd ./program进行确认;它将为您提供程序直接或间接链接的所有库的列表.

If you have ldd installed, you can verify this by running ldd ./program; it will give you a list of all libraries your program has linked with, directly or indirectly.

这篇关于g ++为什么不必须链接iostream二进制文件,而对于pthread却要这样做呢?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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