Contents
1. 推奨ディレクトリ構成
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
my_project/ ├─ CMakeLists.txt # ルートのビルド設定 ├─ .gitignore # 除外対象(後述) ├─ src/ # 実装コード (*.c) │ └─ main.c ├─ include/ # 公開ヘッダ (*.h) │ └─ mylib.h ├─ test/ # ユニットテスト (Catch2 など) │ ├─ CMakeLists.txt │ └─ test_main.c ├─ build/ # ビルド成果物(git 管理外) ├─ docs/ # Doxygen 設定・生成物 └─ scripts/ # 補助スクリプト(version.h 生成等) |
| フォルダ | 主な役割 |
|---|---|
| src | アプリ本体やライブラリ実装。機能単位で module.c のように命名 |
| include | 外部から利用されるヘッダを配置し、#include "mylib.h" だけで参照できる |
| test | テストコードは独立したビルド対象。CI でも実行可能にする |
| build | cmake --build の出力先。.gitignore に必ず追加 |
| docs | Doxygen 設定ファイルや生成物を格納 |
| scripts | バージョンヘッダ自動生成、コード整形などの補助ツール |
この構造は 可読性・拡張性・CI 連携 のすべてに好影響を与えます。
2. ビルドシステム ― Makefile と CMake の比較
2‑1. 選択指針
- 小規模かつ依存がほぼ無いプロトタイプは 単一 Makefile で十分。
- 複数プラットフォーム・外部ライブラリ・テストフレームワークを扱う本格的な開発は CMake が推奨。
2‑2. CMake の最低バージョン
|
1 2 |
cmake_minimum_required(VERSION 3.15) # 3.22 の機能が不要なら 3.15 でも可 |
VERSIONを 3.22 に固定すると、古い Linux ディストリビューションや Windows の CI イメージでインストールが必要になるケースがあります。- 本テンプレートでは 3.15 以上 があれば動作し、
target_precompile_headersやFetchContentといった新機能はオプショナルとして条件分岐させています。
2‑3. CMakeLists.txt(最小構成)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
# ------------------------------------------------- # 基本設定 # ------------------------------------------------- cmake_minimum_required(VERSION 3.15) project(MyProject LANGUAGES C) # デフォルトビルドタイプを Release にする if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release CACHE STRING "" FORCE) endif() # 警告をすべて有効にし、エラー扱いにする(GCC/Clang 用) add_compile_options(-Wall -Wextra -Werror) # インクルードディレクトリ target_include_directories(${PROJECT_NAME} PRIVATE ${CMAKE_CURRENT_SOURCE_DIR}/include) # ソース自動収集 file(GLOB_RECURSE PROJECT_SOURCES CONFIGURE_DEPENDS src/*.c) add_executable(${PROJECT_NAME} ${PROJECT_SOURCES}) # ------------------------------------------------- # テスト設定(Catch2 例) # ------------------------------------------------- enable_testing() add_subdirectory(test) # test/CMakeLists.txt が必要 |
ポイント
target_include_directoriesの第1引数はまだ作成されていないので、PUBLIC/PRIVATEを使う場合はadd_executable後に記述するか、INTERFACEライブラリを介すとエラーが出ません。上記はシンプルさを優先した例です。
2‑4. Windows 環境での注意点
| 作業 | Unix 系コマンド | Windows (PowerShell) |
|---|---|---|
| 実行権限付与 | chmod +x scripts/generate_version.sh |
Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass(一時的にスクリプト実行許可) |
| スクリプト呼び出し | ./scripts/generate_version.sh |
.\scripts\generate_version.ps1 (PowerShell 用に書き換える) |
| CMake ビルド | cmake -B build && cmake --build build |
同上(Git Bash でも可) |
代替スクリプト例(PowerShell)
|
1 2 3 4 5 6 7 8 9 |
# scripts\generate_version.ps1 $version = git describe --tags --always @" #ifndef VERSION_H #define VERSION_H #define PROJECT_VERSION "$version" #endif // VERSION_H "@ | Set-Content -Encoding UTF8 ..\include\version.h |
CMakeLists.txt 側で拡張子を判定し、.sh と .ps1 のどちらかが存在すれば実行するように設定できます。
|
1 2 3 4 5 6 7 8 |
add_custom_target(gen_version ALL COMMAND ${CMAKE_COMMAND} -E env bash ${CMAKE_SOURCE_DIR}/scripts/generate_version.sh # Windows 用 COMMAND powershell -ExecutionPolicy Bypass -File ${CMAKE_SOURCE_DIR}/scripts/generate_version.ps1 WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} ) add_dependencies(${PROJECT_NAME} gen_version) |
3. 自動生成ツール(version.h)活用法
3‑1. 目的
- 一元管理:リポジトリのタグとヘッダ内のバージョン文字列を自動的に同期。手作業による齟齬を防止。
- CI との親和性:ビルド前ステップとして実行すれば、プッシュごとに最新バージョンが組み込まれる。
3‑2. 実装フロー(Unix + Windows 両対応)
-
リポジトリ取得
bash
# Unix 系シェル
git clone https://github.com/yourname/c-template.git my_project
cd my_project/scripts
powershell
# PowerShell
git clone https://github.com/yourname/c-template.git my_project
Set-Location my_project\scripts -
スクリプト実行(自動生成)
- Unix:
./generate_version.sh -
Windows:
.\generate_version.ps1 -
CMake への組み込みは前節の
gen_versionターゲットを参照。 -
コード側で利用
|
1 2 3 4 5 6 7 8 9 |
/* src/main.c */ #include "version.h" #include <stdio.h> int main(void) { printf("MyProject version: %s\n", PROJECT_VERSION); return 0; } |
- GitHub Actions へ組み込み(後述の CI セクションで詳細)
4. Git 管理と .gitignore のベストプラクティス
4‑1. .gitignore のポイント
|
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# ビルド成果物・CMake 関連 /build/ /CMakeCache.txt /CMakeFiles/ # コンパイル生成物 *.o *.obj *.exe *.out *.a *.so *.dll # IDE キャッシュ(VS Code, IntelliJ など) .vscode/* !.vscode/settings.json # ← 個人設定が漏れやすいので除外推奨 .idea/ |
!.vscode/settings.jsonは共有設定でない限り削除
プロジェクト固有のフォーマッタや拡張子関連はsettings.jsonに入ることが多く、個人のエディタテーマやキーバインドまでリポジトリに流出すると情報漏洩リスクがあります。共有したい設定だけをsettings.jsonから抜き出し、.vscode/settings.jsonを 除外(コメントアウト)するか、別ファイル (shared.code-workspace) にまとめて管理してください。
4‑2. 初期化手順とブランチ戦略
|
1 2 3 4 5 6 7 8 9 |
git init git checkout -b develop # 開発用ブランチ作成 git add . git commit -m "Initial skeleton" git branch -M main # 安定版ブランチを main にリネーム git remote add origin https://github.com/yourname/my_project.git git push -u origin main git push -u origin develop |
- 2 本流モデル(
main/develop)は、安定版と開発中コードの境界が明確になるため CI 設定が楽です。 - タグ付けは Semantic Versioning に従い、GitHub Actions で自動的に作成・プッシュするパイプラインを用意すると管理がシンプルです。
4‑3. Windows でも同様のコマンドが利用可能
PowerShell では git 系コマンドはそのまま使用できます。ブランチ名変更は git branch -M main、リモート追加も同一です。
5. VS Code の開発環境設定(CMake Tools + C/C++)
5‑1. 必要な拡張機能
| 拡張 | ID |
|---|---|
| C/C++ | ms-vscode.cpptools |
| CMake Tools | vector-of-bool.cmake-tools |
共有設定は
.vscode/settings.jsonに 以下の項目だけ を残すと安全です
json
{
"cmake.generator": "Ninja",
"C_Cpp.intelliSenseMode": "gcc-x64"
}
5‑2. tasks.json(ビルド・テスト)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
{ "version": "2.0.0", "tasks": [ { "label": "CMake: configure & build", "type": "shell", "command": "cmake", "args": [ "-B", "build", "-S", ".", "-DCMAKE_BUILD_TYPE=Release", "--build", "build" ], "group": "build", "problemMatcher": ["$gcc"] }, { "label": "Run tests", "type": "shell", "command": "ctest", "args": [ "--output-on-failure" ], "options": { "cwd": "${workspaceFolder}/build" }, "group": "test" } ] } |
5‑3. launch.json(デバッグ)
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
{ "version": "0.2.0", "configurations": [ { "name": "(gdb) Launch MyProject", "type": "cppdbg", "request": "launch", "program": "${workspaceFolder}/build/MyProject", "args": [], "stopAtEntry": false, "cwd": "${workspaceFolder}", "environment": [], "externalConsole": false, "MIMode": "gdb" } ] } |
- Windows でのデバッガは
MIModeをlldbやcppvsdbgに変更すれば Visual Studio デバッガが利用できます。
6. CI/CD(GitHub Actions)— 最小構成テンプレート
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 |
name: CI on: push: branches: [ main, develop ] pull_request: branches: [ main, develop ] jobs: build-test: runs-on: ${{ matrix.os }} strategy: matrix: os: [ubuntu-latest, windows-latest] # Linux と Windows 両方で検証 steps: - name: Checkout uses: actions/checkout@v3 with: submodules: true - name: Setup CMake uses: lukka/get-cmake@v3 - name: Generate version.h (Unix) if: runner.os == 'Linux' run: | chmod +x scripts/generate_version.sh ./scripts/generate_version.sh - name: Generate version.h (Windows) if: runner.os == 'Windows' shell: pwsh run: | Set-ExecutionPolicy -Scope Process -ExecutionPolicy Bypass .\scripts\generate_version.ps1 - name: Configure CMake run: cmake -B build -DCMAKE_BUILD_TYPE=Release - name: Build run: cmake --build build --config Release - name: Test run: ctest --output-on-failure --test-dir build |
6‑1. ポイント解説
| ステップ | 内容 |
|---|---|
matrix.os |
Linux と Windows の両方でビルドできるかを同時に検証。クロスプラットフォーム対応の必須チェックです。 |
Generate version.h |
OS 毎に実行権限付与や PowerShell 実行ポリシー設定が異なるため、条件分岐で切り替えています。 |
ctest |
テスト結果は GitHub の Checks に自動掲載され、失敗した場合は PR が赤くなります。 |
7. まとめ
- ディレクトリ構成は
src/ include/ test/ build/ docs/ scripts/をベースにし、役割ごとに明確に分離するだけで CI・IDE の設定が楽になります。 - ビルドは CMake がデフォルト。最低バージョンは 3.15 とし、3.22 固有機能はオプション化すれば古い環境でも問題なく動作します。
- 自動生成ツール(version.h)でタグとコードのバージョンを常に同期させ、CI のビルド前ステップとして組み込むだけで手動ミスが激減します。
- Git 管理では
.gitignoreにビルド成果物・IDE キャッシュを除外し、個人設定(.vscode/settings.json)は共有対象から外すことを推奨。2 本流ブランチと Semantic Versioning タグでリリース管理を標準化します。 - VS Code の統合は
CMake Tools + C/C++拡張だけで完結。tasks.jsonとlaunch.jsonをプロジェクトに入れておけば、メンバー全員が「ビルド / テスト / デバッグ」をワンクリックで実行可能です。 - CI/CDは GitHub Actions のマトリクスジョブで Linux/Windows 両方を検証し、
generate_versionスクリプトの実行やテスト結果の自動レポートを提供します。
これらの手順と設定をそのままプロジェクトにコピーすれば、安全・高速・拡張性の高い C 言語開発基盤が即座に構築できます。ぜひ試してみてください!