Sample structure layout
project(lvis24) cmake_minimum_required(VERSION 3.0) add_subdirectory( bin )
# ignore the build directory build/*
add_subdirectory( tests )
add_subdirectory( hello_world )
Now you can compile it all by
project(lvis24) cmake_minimum_required(VERSION 3.0) add_subdirectory(bin) add_subdirectory(lib)
# cat CMakeLists.txt add_subdirectory( hello_lib )
project( hello_world_lib ) add_library(${PROJECT_NAME} hello_world_lib.cpp hello_world_lib.h) # -shared creates the shared library set_target_properties(${PROJECT_NAME} PROPERTIES COMPILE_FLAGS "-O2 -Wall -shared") # if you wanted to add other libs # target_link_libraries(${PROJECT_NAME} crypto ssl z)
project(hello_world) cmake_minimum_required(VERSION 3.0) add_executable(${PROJECT_NAME} main.cpp) target_link_libraries(${PROJECT_NAME} hello_world_lib) include_directories(../../../lib/hello_lib) link_directories(../../../lib/hello_lib)
Does this work? (spoiler alert… yep!)
lvis@lvis-dell-xps:~/repos/lvis24/build$ cmake .. -- The C compiler identification is GNU 9.4.0 -- The CXX compiler identification is GNU 9.4.0 -- Check for working C compiler: /usr/bin/cc -- Check for working C compiler: /usr/bin/cc -- works -- Detecting C compiler ABI info -- Detecting C compiler ABI info - done -- Detecting C compile features -- Detecting C compile features - done -- Check for working CXX compiler: /usr/bin/c++ -- Check for working CXX compiler: /usr/bin/c++ -- works -- Detecting CXX compiler ABI info -- Detecting CXX compiler ABI info - done -- Detecting CXX compile features -- Detecting CXX compile features - done -- Configuring done -- Generating done -- Build files have been written to: /home/lvis/repos/lvis24/build lvis@lvis-dell-xps:~/repos/lvis24/build$ make Scanning dependencies of target hello_world_lib [ 25%] Building CXX object lib/hello_lib/CMakeFiles/hello_world_lib.dir/hello_world_lib.cpp.o [ 50%] Linking CXX static library libhello_world_lib.a [ 50%] Built target hello_world_lib Scanning dependencies of target hello_world [ 75%] Building CXX object bin/tests/hello_world/CMakeFiles/hello_world.dir/main.cpp.o [100%] Linking CXX executable hello_world [100%] Built target hello_world lvis@lvis-dell-xps:~/repos/lvis24/build$ ./bin/tests/hello_world/hello_world Hello World Hello from the library that you included!
NOTE: This source also has a skeleton of a class so you can see how to create and call your own class.