ʹÓÃCMake¹¹½¨LinuxÂþÑÜʽӦÓóÌÐòµÄÉèÖü¼ÇÉ
ʹÓÃcmake¹¹½¨linuxÂþÑÜʽӦÓóÌÐòµÄÉèÖü¼ÇÉ
СÐò£º
ÔÚ Linux ƽ̨ÉÏ£¬Ê¹Óà CMake ×÷Ϊ¹¹½¨¹¤¾ßÄÜ´ó´ó¼ò»¯ÏîÄ¿µÄÖÎÀíºÍ¹¹½¨Àú³Ì¡£ÓÈÆäÊÇÔÚ¹¹½¨ÂþÑÜʽӦÓóÌÐòʱ£¬Ê¹Óà CMake ¿ÉÒÔÔ½·¢¸ßЧµØÉèÖúÍÖÎÀíÏîÄ¿µÄÒÀÀµÏî¡¢±àÒëÑ¡ÏîµÈ¡£±¾ÎĽ«·ÖÏíһЩʹÓà CMake ¹¹½¨ Linux ÂþÑÜʽӦÓóÌÐòµÄÉèÖü¼ÇÉ£¬ÒÔ×ÊÖú¿ª·¢Õ߸üºÃµØ¹¹½¨ºÍÖÎÀíÂþÑÜʽӦÓá£
Ò»¡¢×°ÖúÍÉèÖà CMake
ÔÚ×îÏÈ֮ǰ£¬È·±£ÒѾÔÚ Linux ϵͳÉÏ×°ÖÃÁË CMake ¹¹½¨¹¤¾ß¡£¿ÉÒÔʹÓÃϵͳ°ü¹ÜÀíÆ÷¾ÙÐÐ×°Öã¬ÀýÈçÔÚ Ubuntu ÉÏ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁî¾ÙÐÐ×°Öãº
sudo apt-get install cmake
µÇ¼ºó¸´ÖÆ
¶þ¡¢½¨Éè CMakeLists.txt Îļþ
CMake ʹÓà CMakeLists.txt ÎļþÀ´ÐÎòÏîÄ¿µÄÉèÖú͹¹½¨ÐÅÏ¢£¬ÐèÒªÔÚÏîÄ¿¸ùĿ¼Ï½¨Éè¸ÃÎļþ¡£ÔÚ CMakeLists.txt ÎļþÖУ¬¿ÉÒÔ½ç˵ÏîÄ¿µÄÃû³Æ¡¢Ô´Îļþ¡¢ÒÀÀµ¿âµÈÐÅÏ¢¡£ÒÔÏÂÊÇÒ»¸ö¼òÆ CMakeLists.txt ÎļþʾÀý£º
# Ö¸¶¨ÏîÄ¿µÄÃû³Æ project(MyApp) # Ö¸¶¨×îµÍ°æ±¾ÒªÇó cmake_minimum_required(VERSION 3.10) # Ìí¼ÓÔ´Îļþ add_executable(myapp main.cpp) # Ìí¼ÓÁ´½ÓµÄ¿â target_link_libraries(myapp pthread)
µÇ¼ºó¸´ÖÆ
ÒÔÉÏʾÀýÖУ¬ÏîÄ¿Ãû³ÆΪ “MyApp”£¬×îµÍ°æ±¾ÒªÇóΪ CMake 3.10¡£Í¨¹ý add_executable ÏÂÁîÌí¼ÓÁËÒ»¸öÃûΪ “myapp” µÄ¿ÉÖ´ÐÐÎļþ£¬²¢Ê¹Óà target_link_libraries ÏÂÁîÁ´½ÓÁËÃûΪ “pthread” µÄ¿â¡£
Èý¡¢Ìí¼Ó×ÓĿ¼ºÍÒÀÀµÏî
ÔÚÂþÑÜʽӦÓóÌÐò¿ª·¢ÖУ¬Í¨³£»áʹÓöà¸öÄ£¿éºÍÒÀÀµÏîÀ´¹¹½¨Ó¦ÓóÌÐò¡£¿ÉÒÔʹÓà CMake µÄ add_subdirectory ºÍ target_link_libraries ÏÂÁîÀ´Ìí¼Ó×ÓĿ¼ºÍÒÀÀµÏî¡£ÒÔÏÂÊÇÒ»¸öʾÀý£º
# Ìí¼Ó×ÓĿ¼ add_subdirectory(module1) add_subdirectory(module2) # Ìí¼ÓÒÀÀµÏî target_link_libraries(myapp module1 module2)
µÇ¼ºó¸´ÖÆ
ÔÚÉÏÊöʾÀýÖУ¬Í¨¹ý add_subdirectory ÏÂÁîÌí¼ÓÁËÃûΪ “module1” ºÍ “module2” µÄ×ÓĿ¼£¬²¢Ê¹Óà target_link_libraries ÏÂÁîÁ´½ÓÁËÕâÁ½¸ö×ÓĿ¼¡£
ËÄ¡¢Ê¹Óà CMake ²ÎÊý»¯ÉèÖÃ
CMake ÔÊÐíʹÓòÎÊýÀ´¶¯Ì¬ÉèÖÃÏîÄ¿¡£ÕâÔÚ¹¹½¨ÂþÑÜʽӦÓóÌÐòʱÌØÊâÓÐÓ㬿ÉÒÔƾ֤²î±ðµÄÉèÖñàÒë²î±ðµÄ´úÂë¡£ÀýÈ磬¿ÉÒÔʹÓà option ÏÂÁî½ç˵һ¸ö¿ª¹Ø±äÁ¿£¬²¢Ê¹Óà if Ìõ¼þÓï¾äƾ֤±äÁ¿µÄÖµ¾ÙÐвî±ðµÄÉèÖá£ÒÔÏÂÊÇÒ»¸öʾÀý£º
# ½ç˵¿ª¹Ø±äÁ¿ option(ENABLE_DEBUG "Enable debug mode" OFF) # ƾ֤Ìõ¼þ¾ÙÐÐÉèÖà if (ENABLE_DEBUG) add_definitions(-DDEBUG) set(CMAKE_BUILD_TYPE Debug) else() set(CMAKE_BUILD_TYPE Release) endif()
µÇ¼ºó¸´ÖÆ
ÒÔÉÏʾÀýÖУ¬½ç˵ÁËÒ»¸öÃûΪ “ENABLE_DEBUG” µÄ¿ª¹Ø±äÁ¿£¬²¢Æ¾Ö¤±äÁ¿µÄÖµÉèÖÃÁ˱àÒëÑ¡Ïî¡£
Î塢ʹÓà CMake ±àÒëºÍ¹¹½¨
Íê³ÉÁË CMakeLists.txt ÎļþµÄÉèÖú󣬿ÉÒÔʹÓà CMake ¾ÙÐбàÒëºÍ¹¹½¨¡£ÔÚÏîÄ¿¸ùĿ¼Ï½¨ÉèÒ»¸öÃûΪ “build” µÄÎļþ¼Ð£¬²¢ÔÚ¸ÃÎļþ¼ÐÖÐÖ´ÐÐÒÔÏÂÏÂÁ
cmake .. make
µÇ¼ºó¸´ÖÆ
ÒÔÉÏÏÂÁî»áƾ֤ CMakeLists.txt ÎļþÖеÄÉèÖÃÐÅÏ¢ÌìÉú Makefile£¬²¢Ö´Ðй¹½¨Àú³Ì¡£
Áù¡¢×ܽá
±¾ÎÄÏÈÈÝÁËʹÓà CMake ¹¹½¨ Linux ÂþÑÜʽӦÓóÌÐòµÄÉèÖü¼ÇÉ¡£Í¨¹ý½¨Éè CMakeLists.txt Îļþ£¬Ìí¼Ó×ÓĿ¼ºÍÒÀÀµÏʹÓòÎÊý»¯ÉèÖõȼ¼ÇÉ£¬¿ÉÒÔ¸ßЧµØÖÎÀíºÍ¹¹½¨ÂþÑÜʽӦÓóÌÐò¡£Ï£ÍûÒÔÉÏÄÚÈÝÄܶԿª·¢ÕßÔÚ Linux ƽ̨ÉϾÙÐÐÂþÑÜʽӦÓóÌÐòµÄ¿ª·¢ºÍ¹¹½¨ÌṩһЩ×ÊÖú¡£
²Î¿¼Á´½Ó£º
CMake Documentation: https://cmake.org/documentation/
Modern CMake: https://cliutils.gitlab.io/modern-cmake/
ÒÔÉϾÍÊÇʹÓÃCMake¹¹½¨LinuxÂþÑÜʽӦÓóÌÐòµÄÉèÖü¼ÇɵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡