Santiago Gil
Santiago Gil

Reputation: 1302

CMake compile project with multiple mains and shared functions

Let's suppose I have two source files A and B. Each one has a main and a public function.

A                 B
|__ main()        |__ main()
|__ foo()         |__ bar()

I want bar method to use foo function. How can I compile this in a CMake project?

With this configuration, B obviusly doesn't know A's foo function.

cmake_minimum_required(VERSION 3.5)
project(My_project)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -O3")

add_executable(A A.cpp)
add_executable(B B.cpp)

This configuration has obviusly both definitions of main.

cmake_minimum_required(VERSION 3.5)
project(My_project)

set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14 -O3")

set(SOURCE_FILES A.cpp)
add_library(A_lib STATIC ${SOURCE_FILES})

add_executable(A A.cpp)
add_executable(B B.cpp)

target_link_libraries(B A_lib)

Is there a way to achieve what I want? I'd like not to combine both mains, or separate foo and A main in two different files. Maybe using C++ headers?

Upvotes: 4

Views: 2263

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409346

Split A into two source files:

  • One containing the main function, and which is used by the A executable target but not the library.

  • One containing the foo function, which is used by the A_lib library target.

Then use the library for the A executable target too.

That's the "best" solution IMO.

You can use preprocessor macros to conditionally compile the main function in A.cpp. But it's not really something I recommend.

Upvotes: 7

Related Questions