Multiple CMakeLists

2019-06-11 01:33发布

Suppose I have a directory structure as follows:

/main.cpp
/CMakeLists.txt
/foo/foo.cpp
/foo/CMakeLists.txt

where my /CMakeLists.txt file contains the following:

project(Test)
add_subdirectory("foo")
add_executable(Test main.cpp foo/foo.cpp)
target_link_libraries(Test ${OpenNI_LIB})

and my /foo/CMakeLists.txt file contains the following:

find_library(OpenNI REQUIRED)

When I use the line add_subdirectory("foo") in the first CMakeLists.txt, what actually happens? Does it search for a second CMakeLists.txt file in foo, and add the contents to the first? Will any variables defined the second file be available in the first? And specifically in this example, will the variable ${OpenNI_LIB} be recognised in the first, given that it is defined in the second?

Thanks.

标签: cmake
1条回答
神经病院院长
2楼-- · 2019-06-11 01:52

Does it search for a second CMakeLists.txt file in foo

Yes, it does

and add the contents to the first?

No it doesn't. It performs a number of configuring actions such as finding libraries etc and a generates separate Makefile and/or other build-time artifacts.

And specifically in this example, will the variable ${OpenNI_LIB} be recognised in the first, given that it is defined in the second?

no, unless such a construction

find_library(OpenNI REQUIRED) # this sets variables for OpenNI
                              # in the context of foo/CMakeLists.txt
set(OpenNI_LIB ${OpenNI_LIB} PARENT_SCOPE) # this copies ${OpenNI_LIB}
                              # into the context of /CMakeLists.txt

is used in foo/CMakeLists.txt

By default variables defined in a subdirectory's CMakeLists.txt are also defined in the subdirectory's subdirectories, that is if foo/ in turn contained bar/ with its own CMakeLists.txt, then within bar/'s CMakeLists.txt ${OpenNI_LIB} would be set.

P.S. message(STATUS "Some message with ${VAR}") in doubtful places of CMakeLists.txt is your friend. Just look into cmake output.

查看更多
登录 后发表回答