C++中头文件的结构,并通过终端Mac进行编译

structure of header files in C++ and compiling via Terminal Mac

本文关键字:终端 Mac 编译 文件 结构 C++      更新时间:2023-10-16

我对头文件的结构感到困惑。在我的程序中,头文件只有一个int add(int x, int y);的正向声明,在main方法中,它调用头文件,但不使用任何返回语句初始化正向声明,它只分配x和y的特定值。换句话说,当头文件中的代码没有任何返回类型时,main方法如何知道该如何处理头文件内的代码。任何帮助都将不胜感激。如果有帮助的话,下面是两个文件的代码:

add.h:

int add(int x, int y); // function prototype for add.h

main.cpp:

#include <iostream>
#include "add.h" // this brings in the declaration for add()
int main()
{
using namespace std;
cout << "The sum of 3 and 4 is " << add(3, 4) << endl;
return 0;
}

我使用g++ add.h main.cpp execution1; ./execution1从终端编译它,得到了这个错误:

clang: warning: treating 'c-header' input as 'c++-header' when in C++ mode, this behavior is deprecated
clang: error: cannot specify -o when generating multiple output files
-bash: ./execution1: No such file or directory

这是重复的,请参阅此处:如何在Mac 上通过命令行编译C++程序

但你回答。。。

您可以使用c++ -c main.cpp,然后使用c++ main.o,它将生成.exe

再见!