camke 入门

Posted by shensunbo on March 12, 2024
  1. 初始目录,使用两个静态库
    1
    2
    3
    4
    5
    6
    7
    8
    
    ├── include
    │   ├── byeworld.h
    │   └── helloworld.h
    ├── lib
    │   ├── libbyeworld.a
    │   └── libhelloworld.a
    └── src
     └── main.cpp
    
  2. 根目录下创建一个CMakeLists.txt, 内容如下
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 # not necessary
cmake_minimum_required(VERSION 3.10)

 # set project name
project(HelloWorld)

 # add .h file path
include_directories(include)

 # add lib file path
link_directories(lib)

 # add executable file
add_executable(helloExe src/main.cpp)

 # link lib 
target_link_libraries(helloExe  byeworld helloworld)

  1. 根目录下创建一个build文件来存放输出文件,build文件夹下执行 cmake .. (cmake 后跟CMakeLists.txt文件的路径)
  2. 执行完之后会输出一些文件,其中有makefile
  3. build文件夹下执行make指令,构建项目,执行结果如下
    1
    2
    3
    4
    5
    
    :~/code/testCode/cmakeTest/build$ make
    Scanning dependencies of target helloExe
    [ 50%] Building CXX object CMakeFiles/helloExe.dir/src/main.cpp.o
    [100%] Linking CXX executable helloExe
    [100%] Built target helloExe
    
  4. 运行编译出的可执行文件
    1
    2
    3
    
    ~/code/testCode/cmakeTest/build$ ./helloExe 
     hello the damn world 
     bye world