c++多文件程序如何写
在C++中,可以使用多个文件来组织程序代码。以下是一个简单的多文件程序的示例:
- 创建一个名为
main.cpp
的文件,作为主文件。
// main.cpp
#include <iostream>
#include "functions.h"
int main() {
int a = 5;
int b = 10;
int result = add(a, b);
std::cout << "The sum of " << a << " and " << b << " is " << result << std::endl;
return 0;
}
- 创建一个名为
functions.h
的头文件,用于声明函数原型。
// functions.h
#ifndef FUNCTIONS_H
#define FUNCTIONS_H
int add(int a, int b);
#endif
- 创建一个名为
functions.cpp
的文件,用于实现函数定义。
// functions.cpp
#include "functions.h"
int add(int a, int b) {
return a + b;
}
- 编译和运行程序。将
main.cpp
、functions.h
和functions.cpp
一起编译成一个可执行文件。
g++ main.cpp functions.cpp -o program
./program
这样就完成了一个简单的多文件程序。main.cpp
是程序的入口,通过#include
指令包含functions.h
头文件,以便在主文件中使用add
函数。functions.h
文件声明了add
函数的原型,然后在functions.cpp
文件中实现了该函数的定义。编译时将所有文件一起编译并链接到一个可执行文件中,然后运行该可执行文件。