Cri*_*ian 5 c++ visual-studio-2012
我刚刚开始学习 C++,我正在使用 Microsoft Visual Studio Express 2012。我开始了一个项目,我计划在其中拥有我所有的 .cpp 文件,但我现在遇到了一个问题,当我尝试编译和运行特定的 . cpp 文件它不起作用。
VS 似乎只是编译并运行其中包含 main 函数的 .cpp 文件,然后生成一个 .exe 并运行它。因此,由于我的第一个 .cpp 文件(包含 main())是一个简单的 hello world 程序,因此当我现在尝试编译和运行时,我只会得到那个。
我有另一个带有 int age() 函数的 .cpp 文件,该函数应该询问用户年龄然后输出它。这非常简单,我只想运行它以查看它的运行情况,但我不知道如何在我的项目中编译该特定的 .cpp 文件,因为它似乎只想用 main( ) 功能。
如何在项目中编译特定的 .cpp?
所有 C++ 程序都从函数开始main。你为什么不尝试age()从打电话main呢?
当然,为此,您需要让 main.cpp 知道有一个名为 的函数age。这就是头文件的用武之地。
因此,您总共需要以下内容:
主程序
#include "age.h"
int main() {
age();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
年龄.h
#ifndef AGE_H
#define AGE_H
int age();
#endif
Run Code Online (Sandbox Code Playgroud)
年龄.cpp
#include "age.h"
int age() {
// Do age stuff.
return 42;
}
Run Code Online (Sandbox Code Playgroud)