使用g ++编译-包括头文件

问题描述 投票:2回答:2

我只是想回答如何在C ++中编译包含简单头文件的main(在ubuntu 12.04中)时遇到一个简单的问题。

命令:

g++ -o main main.cpp add.cpp -Wall

效果很好。但是,这使我对头文件的要点感到困惑。目前,我有一个简单的程序:

#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;

}

我的“ add.cpp”只是将两个数字加在一起。

头文件是否只是功能原型的替代?我需要单独编译头文件还是在命令行中包含所有.cpp文件是否足够?我知道,如果需要更多文件,则需要一个makefile。

c++ header g++
2个回答
3
投票

#include预处理程序代码只是用相应文件的内容替换了#include行,该文件在您的代码中为add.h。使用g ++参数-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

编辑

您还可以直接在cpp文件中编写函数原型,例如(带有NO头文件):

/* add.cpp */
int add(int x, int y) {
    return x + y;
}
/* 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;
}

也可以。但是最好使用头文件,因为原型可以在多个cpp文件中使用,而在更改原型时无需更改每个cpp文件。


0
投票

[使用头文件(例如header.h)时,仅在存在时包括在如上所述的目录中:

〜$ g ++ source1.cpp source2.cpp source3.cpp -o main -Wall

© www.soinside.com 2019 - 2024. All rights reserved.