Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

cmake variable scope, add_subdirectory

Tags:

scope

cmake

I have a CMakeLists.txt in my project root and one in my /src folder. The one in the /src folder only contains a variable with the .cpp files (set (SOURCEFILES main.cpp foo.cpp)) and in the root CMakeLists.txt I do add_subdirectory(src) and later I do add_executable(MyApp ${SOURCEFILES}).

But cmake gives me the error

add_executable called with incorrect number of arguments, no sources provided

How do I get cmake to see the variable? I read that cmake only knows global variables, but that's obviously not the case...

like image 762
blubberbernd Avatar asked Jul 31 '11 18:07

blubberbernd


People also ask

What does Add_subdirectory do in CMake?

Add a subdirectory to the build. Adds a subdirectory to the build. The source_dir specifies the directory in which the source CMakeLists.

How do you set a variable in CMakeLists txt?

You can use the command line to set entries in the Cache with the syntax cmake -D var:type=value , just cmake -D var=value or with cmake -C CMakeInitialCache. cmake .

How do I use environment variables in CMake?

Use the syntax $ENV{VAR} to read environment variable VAR . To test whether an environment variable is defined, use the signature if(DEFINED ENV{<name>}) of the if() command. For general information on environment variables, see the Environment Variables section in the cmake-language(7) manual.

What is Cmake_source_dir?

The path to the top level of the source tree. This is the full path to the top level of the current CMake source tree. For an in-source build, this would be the same as CMAKE_BINARY_DIR .


1 Answers

As mentioned in the documentation of the set command, each directory added with add_subdirectory or each function declared with function creates a new scope.

The new child scope inherits all variable definitions from its parent scope. Variable assignments in the new child scope with the set command will only be visible in the child scope unless the PARENT_SCOPE option is used.

To make the SOURCEFILES assignment visible in the root folder of your project, try:

set (SOURCEFILES main.cpp foo.cpp PARENT_SCOPE)  
like image 166
sakra Avatar answered Nov 27 '22 15:11

sakra