use*_*546 1 c++ visual-studio c++11
我刚开始使用 Visual Studio 2013。直到我开始将 #include "stdafx.h" 放在每个 cpp 文件的开头,我的代码才会编译。当其他人通过Linux终端编译我的代码时,这会导致任何问题吗?如果我简单地从下面的代码中删除 #include "stdafx.h",它会用 g++ 编译 C++11 吗?
#include "stdafx.h"
#include<iostream>
using std::cout; using std::endl; using std::cin;
using namespace std;
int main()
{
cout << "This is an awesome game to play with your friends!"
<< endl << "You have to pick an integer between 10 and 49 and type it in"
<< endl << "Then your friend has to pick an integer between 50 and 99 and type it in."
<< endl << "Through a series of highly advanced calculations starting with their number,"
<< endl << "They regenerate your original number. Have fun!"
<< endl << ""
<< endl << "Please enter your integer number, between 10 and 49:";
int your_int, their_int, factor, sum, calculation, result;
cin >> your_int;
factor = 99 - your_int;
cout << "Factor: " << factor
<< endl << "Now, please enter your friend's integer number between 50 and 99:";
cin >> their_int;
sum = factor + their_int;
calculation = sum / 100 + sum % 100;
result = their_int - calculation;
cout << "The sum is: " << sum
<< endl << "The calculation is : " << calculation
<< endl << "The result is :" << result
<< endl << "My answer was: " << your_int
<< endl << "Your result was: " << result;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
这里似乎有一些误解stdafx.h。首先,它只是一个头文件,其内容和名称都没有任何特殊之处(见下文)。
在 Visual Studio 中使用预编译头文件时,它默认使用stdafx.h并stdafx.cpp完成此操作。
预编译头文件是一种加速编译的方法,通过“预编译”经常使用且很少更改的头文件到一个包中;然后可以在编译项目中的每个文件时使用这个包。它主要包含各种定义。
为了能够使用预编译头,出于语言技术原因,这需要是每个源文件中的第一段代码。因此,当您使用预编译头时,每个源文件的第一行代码必须包含此共享头。如果不是这种情况,则标头之前的预处理器宏定义可能会从根本上改变解析包含文件的方式,从而使预编译标头“无效”。
现在回到 Visual Studio,要在windows.h包含在stdafx.h. stdafx.cpp只是编译器的一个帮助文件,它用来实际生成 pch 文件;作为用户的您永远不会接触此文件。
现在回答你的问题:
选项 1只要您坚持 C++11 标准stdafx.h并在其他任何地方使用可移植代码,将其作为第一个标头包含在任何地方都没有问题。当您使用 Visual Studio 时,您可以使用预编译的头文件,任何 Linux 环境都会将其视为另一个头文件。事实上,其他编译器也具有预编译头文件stdafx.h,当提供正确的构建标志时,它们将能够直接使用。
选项2您可以在项目属性表中禁用预编译头,在C/C++,预编译头下,您可以将预编译头从使用设置为不使用预编译头。不要忘记对 Debug 和 Release 配置执行此操作。关闭此选项后,您不再需要添加stdafx.h到任何文件。我发现 IntelliSense 在使用预编译头文件时效果最好,因此我通常更喜欢将它们保留在小项目中。
stdafx.h如前所述,stdafx.h并不特别。Visual Studio 项目页面,C/C++,预编译头,说明了使用哪个文件名作为预编译头。该文件stdafx.cpp有一个特殊的属性页,与该主题的其他文件不同。它是唯一将预编译头文件设置为 Create 而不是 Use 的文件,因此编译器知道哪个是帮助文件。
完全可以使用不同的名称甚至多个预编译头;它所需要的只是属性页中的一些额外配置。