LoginSignup
0
0

More than 1 year has passed since last update.

CMakeでhello world

Posted at

内容

  • 基本的なCmakeLists.txtの作法について
    • CmakeLists.txtを使ってvisual studio環境(2019)で"hello world"を表示する方法を学ぶ
      • コンパイル対象の指定
      • インクルードパスの追加
      • リンク対象の指定
      • サブフォルダ指定

基本操作

CmakeLists.txtを使ってvisual studio環境(2019)で"hello world"を表示することを目指します

フォルダ構成は以下

.
├── CMakeLists.txt
├── include(project1とproject2からincludeされる.h)
│  └── hello.h
│      
├── project1(exe作成用)
│  ├── CMakeLists.txt
│  └── main.cpp
│      
├── project2(lib作成用)
│  ├── CMakeLists.txt
│  └── hello.cpp

各ソースファイル

main.cpp
#include "hello.h"

int main() {
    hello();
}
hello.h
#pragma once
void hello();
hello.cpp
#include "hello.h"
#include <iostream>

void hello() {
    std::cout << "Hello World" << std::endl;
}

プロジェクトディレクトリ上のCmakeLists.txtは以下
使用言語やインクルードパスの指定、ビルド対象のフォルダ指定などを行う

./CmakeLists.txt
# CMakeのバージョンを設定
cmake_minimum_required(VERSION 3.8)

# プロジェクト名と使用する言語を設定
project(test_cmake CXX)

# インクルードパスを追加する
# サブディレクトリの追加より先に行う必要がある
include_directories(${PROJECT_SOURCE_DIR}/include)

# サブディレクトリを登録
add_subdirectory(project1)
add_subdirectory(project2)

  • cmake_minimum_required()
    • CMakeの最低バージョンを指定
  • project()
    • プロジェクト名と使用する言語を設定
  • include_directories()
    • インクルードパスを追加
      • これでサブディレクトリに追加したフォルダにもインクルードパスが通る
  • add_subdirectory()
    • サブディレクトリを登録
    • 指定したフォルダにCmakeLists.txtがある場合はそのCmakeLists.txtのビルド方法に従う

Project1下のCmakeLists.txt
実行ファイルの作成を行っている

Project1/CmakeLists.txt
# tmp.exeという実行ファイルをmain.cppから作成
add_executable(tmp main.cpp)

# tmpを作る際にhello.libをリンクする
target_link_libraries(tmp hello)
  • add_executable()
    • ビルドする実行ファイルを指定
  • target_link_libraries()
    • リンク対象を指定

Project2下のCmakeLists.txt
実行ファイルの作成を行っている

Project1/CmakeLists.txt
# hello.libといファイルhello.cppから作成
add_library(hello STATIC  hello.cpp)
  • add_library()
    • ビルドするライブラリを指定

以上

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