在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文件中實現了該函數的定義。編譯時將所有文件一起編譯并鏈接到一個可執行文件中,然后運行該可執行文件。