Ich schlage vor, eine kleine Anwendung zu schreiben, die zwei Unterverzeichnisse haben wird. Eine davon kompiliert die ausführbare Datei und die zweite enthält die statisch verknüpfte Bibliothek.
Als Ergebnis wird das Projekt wie folgt aussehen.
Root CMakeLists.txt
Die Haupt-CMakeLists.txt enthält die Einbeziehung aller Unterverzeichnisse.
cmake_minimum_required (VERSION 3.8) project (Example) add_subdirectory (MyStaticLibrary) add_subdirectory (ExampleStatic)
MyStaticLibrary
Als nächstes kommt die statische Bibliothek, die eine Klasse haben wird, die eine Hello World-Nachricht zurückgibt.
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"; }
BeispielStatic
Und dies ist ein Projekt zum Erstellen einer Binärdatei und es enthält die main.cpp-Datei mit der main-Funktion.
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; }
Fazit
Abschließend ist hier das Ergebnis der Ausführung des Programms mit dieser statisch hinzugefügten Bibliothek.