With CMake if we wanted to create different executables with the same main function we could create a library containing the main function (which is in main.cpp
, say) and link it to all execs by:
add_library(main_lib main.cpp)
add_executable(exe1 source1.cpp)
target_link_libraries(exe1 main_lib)
and so on for other executables. This way, however, we have to specify at least one source file for each exec. What if we have no source files and only want to link execs with different libs?
add_executable(exe1) #(1)
target_link_libraries(exe1 some_lib1 main_lib)
Unfortunately, CMake does not allow (1)
. There is an Object Library
that we could use:
add_library(main_lib OBJECT main.cpp)
add_executable(exe1 $<TARGET_OBJECTS:main_lib>) #(2)
target_link_libraries(exe1 some_lib1)
But (2)
produces the following:
CMakeFiles/main_obj.dir/test_caffe_main.cpp.o: In function `main':
test_caffe_main.cpp:(.text+0x0): multiple definition of `main'
CMakeFiles/test_caffe_main.testbin.lib.dir/test_caffe_main.cpp.o:test_caffe_main.cpp:(.text+0x0): first defined here
How can we reuse an object file containing a main function in different executables when there are no other source files?
EDIT: Object Library works very well with main functions. It turned out I did include a second main by a mistake. Sorry for posting it!