为什么在编译过程中需要包含C或CPP声明文件,而不需要像iostream这样的默认库? [英] Why do we need to include the C or CPP declaration files during compilation and not the default libraries like iostream?

查看:150
本文介绍了为什么在编译过程中需要包含C或CPP声明文件,而不需要像iostream这样的默认库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果需要使用我们自己的带有声明的头文件和带有定义的cpp文件来编译CCPP程序,则需要在编译命令中包括带有定义的cpp文件(请参见

If a C or CPP program needs to be compiled with our own header files with declarations and cpp files with definitions, we need to include the cpp files with definitions in the compilation command (See this answer). However, when we write #include <iostream>, we do not include iostream.cpp in the compilation statement like g++ main.cpp iostream.cpp -o main.

如果我们编写自定义声明文件(例如,使用类声明的hello.hpp和具有定义的hello.cpp),则在main.cpp文件的标题中包含hello.hpp之后,需要使用g++ main.cpp hello.cpp -o main对其进行编译.为什么会这样?

If we write our custom declaration files, for instance hello.hpp with class declaration and hello.cpp with the definitions, we need to compile it using g++ main.cpp hello.cpp -o main after including hello.hpp in the header in the main.cpp file. Why is this?

编辑:是否可以为我们的自定义标头和cpp文件模仿标准模板库的行为,以便我们要做的就是仅包含标头,并且声明自动获得编译?如果是,那怎么办?如果没有,为什么不呢?

EDIT: Is it possible that we can imitate the behavior of the standard template library for our custom header and cpp files such that all we have to do is just include the header and the declarations automatically get compiled? If yes, then how? If no, why not?

推荐答案

正在隐式链接标准库.所以

The standard libraries are being implicitly linked against. So

g++ main.cpp -o main

真的是

g++ main.cpp -o main -lstdc++ -lc

其中,libstdc++是c ++标准库,而libc是c标准库.需要明确链接其他库(例如libm).

where libstdc++ is the c++ standard library, and libc is the c standard library. Other libraries need to be explicitly linked against (such as libm).

如果分开编译和链接步骤,这将变得更加清楚:

This becomes more clear if you separate your compile and linking steps:

g++ -c main.cpp -o main.o
g++ -c other.cpp -o other.o
g++ main.o other.o /usr/lib/libstdc++.a /usr/lib/libc.a -o main

在这里,我们将main()函数定义和其他定义(other.cpp)编译为目标文件,并将它们与标准库中现有的已编译函数/类/变量定义组合在一起.

Here we compile our main() function definition and other definitions (other.cpp) into object files, and combine them with the existing compiled function/class/variable definitions in the standard libraries.

请参见共享库创建静态库创建,详细了解定义文件的方式(.c.cpp)变成了库.

See TLDP's pages on Shared Library Creation and Static Library Creation for details on how definition files (.c and .cpp) are turned into libraries.

这篇关于为什么在编译过程中需要包含C或CPP声明文件,而不需要像iostream这样的默认库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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