C++ VScodeで複数ファイルをコンパイル(make)

VScode(Visual Studio Code)でC++の複数ファイルをコンパイルするサンプルです。
(確認環境:Windows 10,MinGWインストール済み)

目次

複数ファイル コンパイルする対象のファイル
コマンドを使用 g++コマンドでコンパイルする場合
VScodeを使用  VScodeでmakeの環境を設定する
  makefileを作成する
  makeコマンドでコンパイルして実行ファイルを作成する
1つのファイル 1つのファイルをコンパイルする場合

コンパイルする対象のファイル

以下の同じフォルダにある3ファイルを対象にコンパイルで実行するファイルを作成します。

Color.h ヘッダーファイル

#include <string>
using namespace std;
class Color
{
// 
private:
	string name;
// 
public:
	void print1();
	void print2();
// 
};

Color.cpp

#include "Color.h"
#include <iostream>
using namespace std;
// 
void Color::print1()
{
	name = "red";
	cout << "The color is " << name << "\n";
	return;
}
// 
void Color::print2()
{
	name = "blue";
	cout << "The color is " << name << "\n";
	return;
}

test1.cpp 実行するファイル

#include "Color.h"

int main() {

	Color c1;
	c1.print1(); // The color is red
	c1.print2(); // The color is blue

	Color *c2 = new Color();
	c2->print1(); // The color is red
	c2->print2(); // The color is blue
	delete c2;
	return 0;
}

 

g++コマンドでコンパイルする場合

g++とは、c++のコンパイラです。

コンパイルを行い実行ファイルを作成します。

vsコードのターミナルで実行します。

D:\Test1>g++ -c Color.cpp -o Color.o

D:\Test1>g++ -c test1.cpp -o test1.o

D:\Test1>g++ -o testout.exe Color.o test1.o

D:\Test1>testout.exe
The color is red
The color is blue
The color is red
The color is blue

1行目は、Color.cppをコンパイルしColor.oファイルを作成します。
3行目は、test1.cppをコンパイルしtest1.oファイルを作成します。
5行目は、Color.oとtest1.oをまとめてtestout.exeファイルを作成します。
7行目は、testout.exeファイルを実行しています。

Color.hのコンパイルは不要です。

 

VScodeでmakeの環境を設定する

ここからは、makeコマンドで複数ファイルをコンパイルする方法です。

1.コマンドプロンプトで、以下のwingetコマンドを実行しmakeをインストールします。

winget install GnuWin32.Make

 

2.vscodeでMakefile Toolsをインストールします。

 

3.ファイル > ユーザー設定 > 設定 > 拡張機能 > Makefile Toolsをクリックします。
「Make Path」で上記でインストールしたmakeのパスを入力します。

C:\Program Files (x86)\GnuWin32\bin

 

makefileを作成する

上記のC++のコードがあるフォルダと同じ階層にmakefileというファイルを作成し以下を記述します。

# comment
testout: calc.o test1.o
	g++ -o testout.exe calc.o test1.o
Color.o: calc.cpp
	g++ -c calc.cpp -o calc.o
test1.o: test1.cpp
	g++ -c test1.cpp -o test1.o

1行目は、コメントです。先頭にシャープ(#)をつけます。
3行目は、calc.oとtest1.oをまとめてtestout.exeを出力します。
5行目は、calc.cppをコンパイルしてcalc.oを出力します。
7行目は、test1.cppをコンパイルしてtest1.oを出力します。

 

makeコマンドでコンパイルして実行ファイルを作成する

D:\Test1>make
g++ -c Color.cpp -o Color.o
g++ -c test1.cpp -o test1.o
g++ -o testout.exe Color.o test1.o

D:\Test1>make
g++ -o testout.exe Color.o test1.o

D:\Test1>

1行目は、makeコマンドを実行しています。
その結果、2-4行目のコマンドが実行され最終的にtestout.exeが作成されます。

6行目は、makeコマンドの2回目の実行です。
その場合は、testout.exeが作成される行のみ実行されます。
Color.oとtest1.oを削除すれば2,3行目の内容が実行されます。

 

1つのファイルをコンパイルする場合

g++ test1.cpp -o testout.exe

g++コマンドで、test1.cppファイルをコンパイルして、testout.exeファイルを出力しています。

実行は、testout.exeを指定します。

D:\Test1>testout.exe
OK

関連の記事

C++ オーバーライドのサンプル

△上に戻る