Visual Studio 如何将多个 C++ 文件编译在一起?
How does Visual Studio compile together multiple C++ files?
我在 visual studio 中有一个简单的项目 main.cpp
、Log.cpp
和 Log.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 运行s 怎么会像预期的那样?
我们包括 main.cpp 和 Log.cpp 中的 Log.h 文件,但这只是函数声明。我们从来没有在main.cpp中包含Log.cpp,那么main.cpp如何得到Log()的函数体呢?
这被称为 linking 的过程。编译器需要知道 return 类型和 Log
class 中函数的签名(这就是你包含 header 的原因),但如果它不会抛出错误找不到函数定义。当它将 cpp 文件编译成 object 代码文件时,它基本上会在函数定义应该去的地方留下“漏洞”。然后 linker 用于 link 那些 object 文件一起成为一个可执行文件。
但是,编译器确实需要知道 class 的数据成员,因为它们决定了 object 占用多少内存,这是 object 创建所必需的。同样,这些包含在 main.
中包含的 header 文件中的 class 定义中
我在 visual studio 中有一个简单的项目 main.cpp
、Log.cpp
和 Log.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 运行s 怎么会像预期的那样?
我们包括 main.cpp 和 Log.cpp 中的 Log.h 文件,但这只是函数声明。我们从来没有在main.cpp中包含Log.cpp,那么main.cpp如何得到Log()的函数体呢?
这被称为 linking 的过程。编译器需要知道 return 类型和 Log
class 中函数的签名(这就是你包含 header 的原因),但如果它不会抛出错误找不到函数定义。当它将 cpp 文件编译成 object 代码文件时,它基本上会在函数定义应该去的地方留下“漏洞”。然后 linker 用于 link 那些 object 文件一起成为一个可执行文件。
但是,编译器确实需要知道 class 的数据成员,因为它们决定了 object 占用多少内存,这是 object 创建所必需的。同样,这些包含在 main.
中包含的 header 文件中的 class 定义中