我只是有一个简单的问题,因为我试图了解如何在 C++ 中编译(在 ubuntu 12.04 中)包含一个简单头文件的 main 。
命令:
g++ -o main main.cpp add.cpp -Wall
Run Code Online (Sandbox Code Playgroud)
工作正常。然而,这让我对头文件的意义感到困惑。目前,我有一个简单的程序:
#include <iostream>
#include "add.h"
using namespace std;
int main () {
int a, b;
cout << "Enter two numbers to add together" << endl;
cin >> a >> b;
cout << "Sum of " << a << " and " << b << " is " << add(a,b) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
我的“add.cpp”只是将两个数字加在一起。
头文件只是函数原型的替换吗?我是否需要单独编译头文件,或者在命令行中包含所有 .cpp 文件就足够了吗?我知道如果我需要更多文件,则需要生成文件。
预处理器代码#include只是将该行替换为代码中#include相应文件的内容。add.h您可以看到使用 g++ argument 预处理后的代码-E。
理论上你可以在头文件中放入任何内容,并且该文件的内容将通过语句复制#include,而不需要单独编译头文件。
您可以将所有cpp文件放在一个命令中,也可以单独编译它们并最后链接它们:
g++ -c source1.cpp -o source1.o
g++ -c source2.cpp -o source2.o
g++ -c source3.cpp -o source3.o
g++ source1.o source2.o source3.o -o source
Run Code Online (Sandbox Code Playgroud)
编辑
您还可以直接在 cpp 文件中编写函数原型(没有头文件):
/* add.cpp */
int add(int x, int y) {
return x + y;
}
Run Code Online (Sandbox Code Playgroud)
/* main.cpp */
#include <iostream>
using namespace std;
int add(int x, int y); // write function protype DIRECTLY!
// prototype tells a compiler that we have a function called add that takes two int as
// parameters, but implemented somewhere else.
int main() {
int a, b;
cout << "Enter two numbers to add together" << endl;
cin >> a >> b;
cout << "Sum of " << a << " and " << b << " is " << add(a,b) << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
它也有效。但最好使用头文件,因为原型可能会在多个 cpp 文件中使用,而无需在原型更改时更改每个 cpp 文件。
| 归档时间: |
|
| 查看次数: |
25698 次 |
| 最近记录: |