一个简单的例子

这是一个简单、完整并且合理的 CMakeLists.txt 的例子。对于这个程序,我们有一个带有头文件与源文件的库文件( MyLibExample ),以及一个带有源文件的应用程序( MyExample )。

  1. # Almost all CMake files should start with this
  2. # You should always specify a range with the newest
  3. # and oldest tested versions of CMake. This will ensure
  4. # you pick up the best policies.
  5. cmake_minimum_required(VERSION 3.1...3.21)
  6. # This is your project statement. You should always list languages;
  7. # Listing the version is nice here since it sets lots of useful variables
  8. project(
  9. ModernCMakeExample
  10. VERSION 1.0
  11. LANGUAGES CXX)
  12. # If you set any CMAKE_ variables, that can go here.
  13. # (But usually don't do this, except maybe for C++ standard)
  14. # Find packages go here.
  15. # You should usually split this into folders, but this is a simple example
  16. # This is a "default" library, and will match the *** variable setting.
  17. # Other common choices are STATIC, SHARED, and MODULE
  18. # Including header files here helps IDEs but is not required.
  19. # Output libname matches target name, with the usual extensions on your system
  20. add_library(MyLibExample simple_lib.cpp simple_lib.hpp)
  21. # Link each target with other targets or add options, etc.
  22. # Adding something we can run - Output name matches target name
  23. add_executable(MyExample simple_example.cpp)
  24. # Make sure you link your targets with this command. It can also link libraries and
  25. # even flags, so linking a target that does not exist will not give a configure-time error.
  26. target_link_libraries(MyExample PRIVATE MyLibExample)

完整的例子可以在此查看 examples folder.

一个更大,并且包含多文件的例子可在此查看 also available.