温馨提示×

c++多文件程序如何写

c++
小亿
142
2023-10-31 09:14:05
栏目: 编程语言

在C++中,可以使用多个文件来组织程序代码。以下是一个简单的多文件程序的示例:

  1. 创建一个名为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;
}
  1. 创建一个名为functions.h的头文件,用于声明函数原型。
// functions.h

#ifndef FUNCTIONS_H
#define FUNCTIONS_H

int add(int a, int b);

#endif
  1. 创建一个名为functions.cpp的文件,用于实现函数定义。
// functions.cpp

#include "functions.h"

int add(int a, int b) {
    return a + b;
}
  1. 编译和运行程序。将main.cppfunctions.hfunctions.cpp一起编译成一个可执行文件。
g++ main.cpp functions.cpp -o program
./program

这样就完成了一个简单的多文件程序。main.cpp是程序的入口,通过#include指令包含functions.h头文件,以便在主文件中使用add函数。functions.h文件声明了add函数的原型,然后在functions.cpp文件中实现了该函数的定义。编译时将所有文件一起编译并链接到一个可执行文件中,然后运行该可执行文件。

0