Evgenii Legotckoi
Evgenii Legotckoi12. Dezember 2018 15:57

CMake-Projekt mit Unterverzeichnissen und statischer Bibliothek

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.

Projekt mit statischer Bibliothek


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.

Beispiel eines statischen Projekts

Рекомендуємо хостинг TIMEWEB
Рекомендуємо хостинг TIMEWEB
Stabiles Hosting des sozialen Netzwerks EVILEG. Wir empfehlen VDS-Hosting für Django-Projekte.

Magst du es? In sozialen Netzwerken teilen!

Kommentare

Nur autorisierte Benutzer können Kommentare posten.
Bitte Anmelden oder Registrieren
Letzte Kommentare
ИМ
Игорь Максимов5. Oktober 2024 07:51
Django – Lektion 064. So schreiben Sie eine Python-Markdown-Erweiterung Приветствую Евгений! У меня вопрос. Можно ли вставлять свои классы в разметку редактора markdown? Допустим имея стандартную разметку: <ul> <li></li> <li></l…
d
dblas55. Juli 2024 11:02
QML - Lektion 016. SQLite-Datenbank und das Arbeiten damit in QML Qt Здравствуйте, возникает такая проблема (я новичок): ApplicationWindow неизвестный элемент. (М300) для TextField и Button аналогично. Могу предположить, что из-за более новой верси…
k
kmssr8. Februar 2024 18:43
Qt Linux - Lektion 001. Autorun Qt-Anwendung unter Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lektion 007. Arbeiten mit ICMP-Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVA25. Dezember 2023 10:30
Boost - statisches Verknüpfen im CMake-Projekt unter Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
Jetzt im Forum diskutieren
J
JacobFib17. Oktober 2024 03:27
добавить qlineseries в функции Пользователь может получить любые разъяснения по интересующим вопросам, касающимся обработки его персональных данных, обратившись к Оператору с помощью электронной почты https://topdecorpro.ru…
JW
Jhon Wick1. Oktober 2024 15:52
Indian Food Restaurant In Columbus OH| Layla’s Kitchen Indian Restaurant If you're looking for a truly authentic https://www.laylaskitchenrestaurantohio.com/ , Layla’s Kitchen Indian Restaurant is your go-to destination. Located at 6152 Cleveland Ave, Colu…
КГ
Кирилл Гусарев27. September 2024 09:09
Не запускается программа на Qt: точка входа в процедуру не найдена в библиотеке DLL Написал программу на C++ Qt в Qt Creator, сбилдил Release с помощью MinGW 64-bit, бинарнику напихал dll-ки с помощью windeployqt.exe. При попытке запуска моей сбилженной программы выдаёт три оши…
F
Fynjy22. Juli 2024 04:15
при создании qml проекта Kits есть но недоступны для выбора Поставил Qt Creator 11.0.2. Qt 6.4.3 При создании проекта Qml не могу выбрать Kits, они все недоступны, хотя настроены и при создании обычного Qt Widget приложения их можно выбрать. В чем может …

Folgen Sie uns in sozialen Netzwerken