来源:
https://stackoverflow.com/questions/9017573/define-preprocessor-macro-through-cmake
https://stackoverflow.com/questions/28597351/how-do-i-add-a-library-path-in-cmake

目录添加预编译宏

Adds preprocessor definitions to the compiler command line for targets in the current directory and below (whether added before or after this command is invoked).

add_compile_definitions(OPENCV_VERSION=${OpenCV_VERSION})
add_compile_definitions(WITH_OPENCV2)

给指定工程添加预编译宏

Specifies compile definitions to use when compiling a given .

target_compile_definitions(my_target PRIVATE FOO=1 BAR=1)

添加include目录,添加link目录,link指定库

简单的方法如下,

include_directories(${CMAKE_SOURCE_DIR}/inc)
link_directories(${CMAKE_SOURCE_DIR}/lib)

add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # libbar.so is found in ${CMAKE_SOURCE_DIR}/lib

现代cmake一般不这样,上面的命令会对当前目录下的所有target添加-L flag,而不是对所有链接bar的target添加-L参数。下面看下现代cmake的做法:

add_library(bar SHARED IMPORTED) # or STATIC instead of SHARED
set_target_properties(bar PROPERTIES
  IMPORTED_LOCATION "${CMAKE_SOURCE_DIR}/lib/libbar.so"
  IMPORTED_IMPLIB "${CMAKE_SOURCE_DIR}/lib/libbar.lib" 
  INTERFACE_INCLUDE_DIRECTORIES "${CMAKE_SOURCE_DIR}/include/libbar"
)

set(FOO_SRCS "foo.cpp")
add_executable(foo ${FOO_SRCS})
target_link_libraries(foo bar) # also adds the required include path

在windows上指定x86 vs x64

cmake -A win32 ..

这个方法不太好,好像只能适用于vs,下面的方法虽然麻烦些,但是toolchain file应该才是正解:

# the name of the target operating system
set(CMAKE_SYSTEM_NAME Linux)

# which compilers to use for C and C++
set(CMAKE_C_COMPILER gcc)
set(CMAKE_C_FLAGS -m32)
set(CMAKE_CXX_COMPILER g++)
set(CMAKE_CXX_FLAGS -m32)

# here is the target environment located
set(CMAKE_FIND_ROOT_PATH   /usr/i486-linux-gnu )

# adjust the default behaviour of the FIND_XXX() commands:
# search headers and libraries in the target environment, search
# programs in the host environment
set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)

用法很简单:

$ cmake -DCMAKE_TOOLCHAIN_FILE=toolchain.cmake /path/to/source

通过命令行设置unicode支持

这样cmake会把命令行参数直接传给MSBuild,cmake是不关心这些的,这个可能只有vs才适用

cmake --build . -- /p:CharacterSet=Unicode
posted on 2020-03-06 17:05  ConfuciusPei  阅读(227)  评论(0编辑  收藏  举报