cmake tutorial -- 入門

參考鏈接:

快速入門

cmake vs visual studio

參照visual studio來記住cmake的相關命令

VISUAL STUDIO CMAKE COMMAND
Solution file (.sln) project
Project file (.vcproj) target name in the command add_executable or add_library
executable (.exe) add_executable
static library (.lib) add_library
dynamic library (.dll) add_library(SHARED)
Source Folders source_group
Project Folders set_property(TARGET PROPERTY FOLDER)
Properties->General->Output Directory set_target_properties(PROPERTIES RUNTIME_OUTPUT_DIRECTORY)
Properties->C/C+±>Preprocessor->Preprocessor Definitions add_definitions
Properties->C/C+±>General->Additional Include Directories include_directories
Properties->Linker->General->Additional Library Directories link_directories
Properties->Linker->Input->Additional Dependencies target_link_libraries

快速入門

  • 環境: win10 visual studio code wsl linux
  • 創建main.cpp, 創建簡單的 c++ hello world
#include <iostream>

int main(int argc,char* args[])
{
    std::cout<<"Hello World!"<<std::endl;
    return 0;
}
  • 在同級源文件夾下面創建CMakeLists.txt
# cmake 最低支持的版本
cmake_minimum_required(VERSION 3.0)

# 工程名稱
project (cmake_tutorial)

# 添加源文件的文件夾 到DIR_SRCS的變量裏面
aux_source_directory(. DIR_SRCS)

# 生成運行文件 使用DIR_SRCS裏面爲源文件
add_executable(main ${DIR_SRCS})
  • 在vs code的terminal中使用wsl(linux子系統),輸入cmake .,然後再輸入make,就能看見輸出的main執行文件
  • 輸入./main,看到Hello World!輸出成功,即成功跑通cmake的第一個示例程序。在windows下使用類似,make命令需要更換成msbuild或者直接使用visual studio編譯。

cmake 子目錄

  • 創建TestDir子目錄,創建Test.h Test.cpp文件
\\Test.h
class Test
{
    public:
        int add(int a,int b);
};
\\Test.cpp
#include "Test.h"

int Test::add(int a,int b)
{
    return a+b;
}
  • TestDir中創建CMakeLists.txt文件,在cmake工程中,每一級文件夾都建議創建一個CMakeLists.txt文件
#生成靜態庫
add_library(Test Test.cpp)
  • 回到main.cpp同級目錄,修改CMakeLists.txt文件
# cmake 最低支持的版本
cmake_minimum_required(VERSION 3.0)

# 工程名稱
project (cmake_tutorial)

# 添加源文件的文件夾 到DIR_SRCS的變量裏面
aux_source_directory(. DIR_SRCS)

# 添加子目錄
add_subdirectory(TestDir)

# 生成運行文件 使用DIR_SRCS裏面爲源文件
add_executable(main ${DIR_SRCS})

# 添加Test靜態庫
target_link_libraries(main Test)
  • 修改main.cpp文件
#include <iostream>
#include "TestDir/Test.h"

int main(int argc,char* args[])
{
    Test* test=new Test();
    int result=test->add(100,102);
    std::cout<<"Hello World!"<<"Test add Result:"<< result <<std::endl;
    return 0;
}
  • 如上面生成測試,成功輸出:Hello World!Test add Result:202。這樣在不使用visual studio的環境下,也能成功實現了一個自動管理的構建系統,並且支持跨平臺。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章