To create a library use the add_library
command:
add_library(<name> [STATIC | SHARED | MODULE]
[EXCLUDE_FROM_ALL]
source1 source2 ... sourceN)
For example:
add_library(mylib SHARED
a.h
a.cpp
b.h
b.cpp)
Would create a shared library from the four files listed.
If your program (created with add_executable
) uses the library, when you specify the link with target_link_libraries
, CMake will add the dependency, so that if you changed a.cpp the library mylib would be rebuilt and your application would be re-linked.
For example
add_executable(myprog
main.cpp)
target_link_libraries(myprog
mylib)
Edit:
When your library and project are in different folders, you can use add_subdirectory
.
Create a CMakeList.txt in each directory, in the library folder use add_library
in the application, use add_program
and target_link_libraries
.
In the parent folder use add_subdirectory
, add the library folder first, then the program folder. This will make the library available to the application. Then run cmake against the parent CMakeList.