如何在单个 C++ 程序中编译多个翻译单元

问题描述 投票:0回答:1

所以我明白了翻译单元和

.cpp
文件之间的区别;但是,我正在尝试测试内部和外部链接如何工作。我引用我的教科书:

具有外部链接的名称可供其他翻译单元使用。

一个名称怎么可能可供多个翻译单位使用?我相信您可以将多个翻译单元编译到一个

.obj
文件中,但如何在 Visual Studio 中做到这一点?

我知道当你编译一个包含`#include"OTHER_FILE.cpp"的文件时,它仍然是一个翻译单元。我尝试在 Stackoverflow 上查找有关如何在 C++ 程序中编译多个翻译单元的信息,但所有帖子都解释了文件和翻译单元之间的区别,而不是实际上如何为程序创建多个翻译单元。

任何解释都会很棒。

c++ visual-studio compilation
1个回答
0
投票

头文件(

.hpp
文件)的全部目的是声明相应源文件中存在的内容。这样其他源文件就可以使用它。

quux.hpp

#ifndef QUUX_HPP
#define QUUX_HPP

// Here we declare that a variable named ‘quux_value’ exists in “quux.cpp”
// and it can be accessed by code in other .cpp files.
extern int quux_value;

// Here we declare that a function named ‘quuxify’ exists in “quux.cpp”
// and it can be invoked by code in other .cpp files.
int quuxify( int );

#endif

我们的

quux.cpp
可能看起来像这样:

#include "quux.hpp"

int quux_value;

int quuxify( int x )
{
    return x * quux_value;
}

如果我们希望

.cpp
文件中的内容可供其他
.cpp
文件使用,只需不要在
.hpp
文件中声明它们即可。

现在我的主程序可以使用“quux”的东西了

  1. 包括
    quux.hpp
    标头定义,以及
  2. 与已编译的
    quux.o
    目标文件链接。
#include <iostream>
#include "quux.hpp"

int main()
{
    quux_value = 3;
    std::cout << quuxify( 4 ) << "\n";
}

有两个翻译单元:“quux”以及您为包含

main()
的文件命名的任何内容。

编译并将它们链接到一个可执行文件中,它将打印出

12


编辑:顺便说一句,这是一个有点简化的解释,但它是正确的并且可以帮助您入门。请注意,还有此处未提及的其他可见度阴影。
© www.soinside.com 2019 - 2024. All rights reserved.