I propose to write a small application that will have two subdirectories. One of which will compile the executable file, and the second will contain a statically linked library.
As a result, the project will look like this.
Root CMakeLists.txt
The main CMakeLists.txt will contain the connection of all subdirectories.
cmake_minimum_required (VERSION 3.8) project (Example) add_subdirectory (MyStaticLibrary) add_subdirectory (ExampleStatic)
MyStaticLibrary
Next comes the static library, which will have a class that returns a Hello World message.
CMakeLists.txt
cmake_minimum_required (VERSION 3.8) project(MyStaticLibrary) set(SOURCE_FILES "MyStaticLibrary.cpp") set(HEADER_FILES "MyStaticLibrary.h") # We declare the project as a static library and add all the source code files to it. add_library(MyStaticLibrary STATIC ${HEADER_FILES} ${SOURCE_FILES})
MyStaticLibrary.h
#pragma once #include <string> class MyStaticLibrary { public: static std::string getMyStaticMessage(); };
MyStaticLibrary.cpp
#include "MyStaticLibrary.h" std::string MyStaticLibrary::getMyStaticMessage() { return "Hello world from static library"; }
ExampleStatic
And this is a project for creating a binary and it contains the main.cpp file with the main function.
CMakeLists.txt
cmake_minimum_required (VERSION 3.8) project(ExampleStatic) set(SOURCE_FILES "main.cpp") add_executable (ExampleStatic ${SOURCE_FILES}) # Connecting the library, specify where to get the header files include_directories("../MyStaticLibrary") # And also we specify dependence on static library target_link_libraries(ExampleStatic MyStaticLibrary)
main.cpp
#include <iostream> #include "MyStaticLibrary.h" using namespace std; int main() { cout << MyStaticLibrary::getMyStaticMessage() << endl; return 0; }
Conclusion
As a conclusion, here is the result of the work of the program with this statically added library.