Cmake 学习笔记
程序员文章站
2024-02-01 18:13:52
编写CMakeLists.txt #在当前目录新建一个build目录,然后cd build;cmake .. #这样的好处是,可以将cmake生成的内容,和源码文件分离 #设置编译结果发布路径 set( CMAKE_INSTALL_PREFIX ./_install) #配置一个头文件,可以让一些c ......
编写cmakelists.txt
#在当前目录新建一个build目录,然后cd build;cmake ..
#这样的好处是,可以将cmake生成的内容,和源码文件分离
#设置编译结果发布路径
set( cmake_install_prefix ./_install)
#配置一个头文件,可以让一些cmake设置传到源码里,比如可以传版本号,传宏定义等等
configure_file ( "${project_source_dir}/tutorialconfig.h.in" "${project_binary_dir}/tutorialconfig.h" )
#将可执行文件与其源码关联起来
add_executable(tutorial tutorial.c)
#如果是很多源码,可以写一个变量,先把源码文件收集起来,比如下面这样,
set(src_files avl.c rb.c splay.c) add_executable(tutorial ${src_files})
#增加库文件
add_library(mathfunctions mysqrt.cxx)
#增加动态库,src_tree_files是实现定义好的源码文件列表
add_library(tree shared ${src_tree_files})
#增加静态库
add_library(tree_static static ${src_tree_files})
#将库文件和可执行文件链接起来
target_link_libraries (tutorial mathfunctions)
#如何连接系统库,但是必须在add_executable之前加才有效
link_libraries(-lpthread -lm)
#验证系统是否提供某些函数
# does this system provide the log and exp functions?
include (checkfunctionexists) check_function_exists (log have_log) check_function_exists (exp have_exp)
#也还需要在配置文件tutorialconfig.h中增加,这样源码中就能用这个宏定义来确定函数是否支持
#cmakedefine have_log #cmakedefine have_exp
#可以增加头文件搜索路径
include_directories ("${project_binary_dir}")
#或者为某一个目标添加
target_include_directories(os_demo private ${cmake_source_dir} ${cmake_source_dir}/inc )
#如何添加编译选项; 设置编译选项可以通过add_compile_options命令,也可以通过set命令修改cmake_cxx_flags或cmake_c_flags
set(cmake_c_flags "-o3 -ffast-math -wall -std=gnu99 -fpic")
#疑问?
${cmake_current_binary_dir},${project_source_dir},${project_binary_dir}在哪定义的
#通过打印显示;cmake_current_binary_dir,project_binary_dir是当前目录,project_source_dir是cmakelists.txt所在目录。
-- this is the engine cmake_current_binary_dir: /home/xxxx/engine/build.tx1
-- this is the engine project_source_dir: /home/xxxx/engine
-- this is the engine project_binary_dir: /home/xxxx/build.tx1
#如何方便的进行交叉编译?一般要用到cmake_toolchain_file
cmake .. -dcmake_toolchain_file=../tx1.toolchain.cmake
#下面是一个简单的toolchain.cmake例子
# this is required set(cmake_system_name linux) # specify the cross compiler set(cmake_c_compiler /opt/nvidia/gcc-linaro-5.3.1-2016.05-x86_64_aarch64-linux-gnu//bin/aarch64-linux-gnu-gcc) set(cmake_cxx_compiler /opt/nvidia/gcc-linaro-5.3.1-2016.05-x86_64_aarch64-linux-gnu//bin/aarch64-linux-gnu-g++) # where is the target environment set(cmake_find_root_path /opt/nvidia/gcc-linaro-5.3.1-2016.05-x86_64_aarch64-linux-gnu/aarch64-linux-gnu/include/c++/5.3.1) # search for programs in the build host directories (not necessary) set(cmake_find_root_path_mode_program never) # for libraries and headers in the target directories set(cmake_find_root_path_mode_library only) set(cmake_find_root_path_mode_include only)