Visual Studio如何将多个C ++文件编译在一起?

时间:2020-11-10 03:13:32

标签: c++ compilation linker include

我在Visual Studio中有一个简单的项目,其中包含main.cppLog.cppLog.h

main.cpp:

#include <iostream>
#include "Log.h"

int main()
{
    Log("Hello World");
    std::cin.get();
}

Log.cpp

#include <iostream>
#include "Log.h"

void Log(std::string message)
{
    std::cout << message << std::endl;
}

void InitLog()
{
    Log("Initialized Logger");
}

Log.h:

#pragma once
#include <string>

void Log(std::string);
void InitLog();

我知道#include语句将所有包含文件的代码复制粘贴到写入该文件的文件中。我的问题是,当我运行它时,Log函数是否按预期运行?

我们同时包含来自main.cpp和Log.cpp的Log.h文件,但这仅是函数声明。我们永远不会在main.cpp中包含Log.cpp,那么main.cpp如何获得Log()的函数体?

1 个答案:

答案 0 :(得分:1)

这称为链接的过程。编译器需要知道Log类中函数的返回类型和签名(这就是为什么要包含标头的原因),但是如果找不到函数定义,它就不会抛出错误。当它将cpp文件编译为目标代码文件时,基本上会留下“漏洞”,这些漏洞应该在函数定义中存在。然后使用链接器将这些目标文件链接到一个可执行文件中。

但是,编译器确实需要知道您的类的数据成员,因为那些数据成员确定对象占用多少内存,这对于创建对象是必需的。同样,它们包含在main头文件中的类定义中。