Evgenii Legotckoi
Dec. 13, 2018, 2:57 a.m.

CMake project with subdirectories and static library

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.

Project with static library


Root CMakeLists.txt

The main CMakeLists.txt will contain the connection of all subdirectories.

  1. cmake_minimum_required (VERSION 3.8)
  2.  
  3. project (Example)
  4.  
  5. add_subdirectory (MyStaticLibrary)
  6. add_subdirectory (ExampleStatic)

MyStaticLibrary

Next comes the static library, which will have a class that returns a Hello World message.

CMakeLists.txt

  1. cmake_minimum_required (VERSION 3.8)
  2.  
  3. project(MyStaticLibrary)
  4.  
  5. set(SOURCE_FILES "MyStaticLibrary.cpp")
  6. set(HEADER_FILES "MyStaticLibrary.h")
  7.  
  8. # We declare the project as a static library and add all the source code files to it.
  9. add_library(MyStaticLibrary STATIC ${HEADER_FILES} ${SOURCE_FILES})

MyStaticLibrary.h

  1. #pragma once
  2.  
  3. #include <string>
  4.  
  5. class MyStaticLibrary
  6. {
  7. public:
  8. static std::string getMyStaticMessage();
  9. };

MyStaticLibrary.cpp

  1. #include "MyStaticLibrary.h"
  2.  
  3. std::string MyStaticLibrary::getMyStaticMessage()
  4. {
  5. return "Hello world from static library";
  6. }

ExampleStatic

And this is a project for creating a binary and it contains the main.cpp file with the main function.

CMakeLists.txt

  1. cmake_minimum_required (VERSION 3.8)
  2.  
  3. project(ExampleStatic)
  4.  
  5. set(SOURCE_FILES "main.cpp")
  6.  
  7. add_executable (ExampleStatic ${SOURCE_FILES})
  8.  
  9. # Connecting the library, specify where to get the header files
  10. include_directories("../MyStaticLibrary")
  11. # And also we specify dependence on static library
  12. target_link_libraries(ExampleStatic MyStaticLibrary)

main.cpp

  1. #include <iostream>
  2.  
  3. #include "MyStaticLibrary.h"
  4.  
  5. using namespace std;
  6.  
  7. int main()
  8. {
  9. cout << MyStaticLibrary::getMyStaticMessage() << endl;
  10. return 0;
  11. }

Conclusion

As a conclusion, here is the result of the work of the program with this statically added library.

Example static project

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html