0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

MakefileとCMakeの違いを理解する

Last updated at Posted at 2025-05-03

概要

MakefileとCMakeがどういうものなのか、C++で簡単なサンプルを使って理解する。
<サンプル内容>
test1:シンプルにビルド
test2:Makefileを使ってビルド
test3:CMakeを使ってビルド

test1:シンプルにビルド

フォルダ構成(ビルド前)
test1
└── foo.cpp

test1フォルダに、foo.cppファイルを作成する

foo.cpp
#include <iostream>
int main(){
    std::cout << "Hello world!\n";
}

コマンドからg++でビルドする。
実行ファイル(main)ができて、実行すると”Hello world”が表示される。

コマンドライン
$ g++ foo.cpp -o main
$ ./main
Hello world!

コマンド実行後のフォルダ構成

フォルダ構成(ビルド後)
test1
├── foo.cpp
└── main

とてもシンプル。

test2:Makefileを使ってビルド

フォルダ構成(ビルド前)
test2
├── foo.cpp
└── Makefile

次はtest2フォルダに、foo.cppとMakefileを用意する。
(foo.cppは、test1と同じなので省略)

Makefile
OBJS = foo.cpp
PROG = main

$(PROG):
	g++ $(OBJS) -o $(PROG)

コマンドからmakeと打つことで、Makefileが実行される。
できあがったmain(実行ファイル)を実行すると、”Hello world”が表示される。

コマンドライン
$ make
$ ./main
Hello world!

コマンド実行後のフォルダ構成

フォルダ構成(ビルド後)
test2
├── foo.cpp
├── Makefile
└── main

makefileは別にビルド専用ではないのでいろいろ使える(意外と便利)

test3:CMakeを使ってビルド

フォルダ構成(ビルド前)
test3
├── foo.cpp
├── CMakeLists.txt
└── build

test3フォルダに、foo.cppとCMakeLists.txtを用意する。
test3フォルダに、buildフォルダを作成する。
(buildフォルダは、ビルドの結果できる生成物を格納するためのフォルダ。
 なお、foo.cppは、test1/test2と同じ。)

CMakeLists.txt
cmake_minimum_required(VERSION 3.10)
project(test3 CXX)
add_executable(main foo.cpp)

コマンドからbuildフォルダに移動して、cmake ..を実行する。
上の階層のCMakeLists.txtの内容に従って、buildフォルダにmakefileが作成される。
次にmakeを実行すると、作成されたmakefileを使ってビルド実行する。
最後に実行ファイル(main)を実行すると、”Hello world”が表示される。

コマンドライン
$ cd build
$ cmake ..
$ make
$ ./main
Hello world!

コマンド実行後のフォルダ構成(ビルドフォルダには、他にもファイルできる)

フォルダ構成(ビルド後)
test3
├── foo.cpp
├── CMakeLists.txt
└── build
   ├── makefile
   └── main

<ポイント>
・CMakeは、MakeLists.txtの内容に従って、実行環境にあわせたmakefileを作る。
・CMakeしたあとに、makefileを実行させるので、makeが必要になる。
この辺りが、よくわかっていなかった。
オプションなどがたくさんつくとわかりにくいが、理解すればシンプルかも。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?