johnbakers
johnbakers

Reputation: 24750

Adding sources to a list variable in cmake vs. directly in add_executable

Why is it recommended to add sources to a list first, rather than directly to the executable?

PROJECT( helloworld )
SET( hello_SRCS hello.cpp )
ADD_EXECUTABLE( hello ${hello_SRCS} )

Why not just skip the SET line altogether?

Upvotes: 2

Views: 3644

Answers (1)

galsh83
galsh83

Reputation: 570

I have seen this practice often enough to also think that it’s considered a good practice. For example, if you use the CLion IDE (which actually uses CMakeLists.txt as its project structure file), you’ll see that when you create a new project it creates a SOURCE_FILES variable by default.

One reason I can think of as to why this is a good practice is that if you want to build the same files into several targets. For example, you might want to have both static and shared binaries for your lib, so if you have a SOURCE_FILES var you just have to write something like:

add_library(myLibStatic STATIC ${SOURCE_FILES})
add_library(myLibShared SHARED ${SOURCE_FILES})

Upvotes: 4

Related Questions