複数のファイルを使用した C++ プログラムの書き方
C++では、複数のファイルを使ってプログラムのコードを分割できます。以下に、簡単なマルチファイルプログラムの例を示します:
- mein.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
- 関数のheaderファイル
- functions.cpp
g++ main.cpp functions.cpp -o program
./program
この通りで、簡単なマルチファイル・プログラムが完成した。main.cpp はプログラムのエントリポイントであり、#include ディレクティブを介して functions.h ヘッダ・ファイルを取り込み、add 関数をメインファイルで使用できる。functions.h ファイルは add 関数のプロトタイプを宣言し、functions.cpp ファイルでは関数の定義が実装される。コンパイル時にはすべてのファイルがまとめてコンパイルされ、実行可能ファイルにリンクされてから、実行される。