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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With