ʹÓÃCMake¹¹½¨Linux¶àÏß³ÌÓ¦ÓóÌÐòµÄÉèÖü¼ÇÉ
ʹÓÃcmake¹¹½¨linux¶àÏß³ÌÓ¦ÓóÌÐòµÄÉèÖü¼ÇÉ
ÔÚLinuxƽ̨ÉÏ¿ª·¢¶àÏß³ÌÓ¦ÓóÌÐòÊÇÒ»Ïî³£¼ûµÄʹÃü¡£CMakeÊÇÒ»¸öÇ¿Ê¢µÄ¹¹½¨¹¤¾ß£¬Ëü¿ÉÒÔ¼ò»¯ÏîÄ¿µÄ¹¹½¨Àú³Ì¡£±¾ÎĽ«ÏÈÈÝÔõÑùʹÓÃCMakeÉèÖú͹¹½¨¶àÏß³ÌÓ¦ÓóÌÐò£¬²¢¸ø³öһЩ´úÂëʾÀý¡£
Ê×ÏÈ£¬È·±£ÒѾװÖÃÁËCMake¡£ÔÚÖÕ¶ËÖÐÊäÈëÒÔÏÂÏÂÁîÀ´¼ì²éCMakeÊÇ·ñÒÑ×°Öãº
cmake --version
µÇ¼ºó¸´ÖÆ
ÈôÊÇCMakeÒѾװÖ㬽«ÏÔʾÆä°æ±¾ÐÅÏ¢¡£ÈôÊÇδװÖã¬Çëƾ֤ÄúµÄLinux¿¯Ðаæ×°ÖÃCMake¡£
½ÓÏÂÀ´£¬ÎÒÃǽ«½¨ÉèÒ»¸ö¼òÆӵĶàÏß³ÌÓ¦ÓóÌÐò£¬ÒÔ˵Ã÷ÔõÑùʹÓÃCMake¾ÙÐÐÉèÖá£
Ê×ÏÈ£¬½¨ÉèÒ»¸öÃûΪ”main.cpp”µÄÎļþ£¬²¢ÔÚÆäÖбàдÒÔÏ´úÂ룺
#include <iostream> #include <thread> void threadFunction() { std::cout << "This is a thread." << std::endl; } int main() { std::thread t(threadFunction); t.join(); std::cout << "This is the main thread." << std::endl; return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃǽç˵ÁËÒ»¸öÃûΪthreadFunctionµÄº¯Êý£¬²¢ÔÚÆäÖÐÊä³öÒ»ÌõÐÂÎÅ¡£ÔÚmainº¯ÊýÖУ¬ÎÒÃǽ¨ÉèÁËÒ»¸öеÄỊ̈߳¬È»ºóʹÓÃjoinº¯ÊýÆÚ´ý¸ÃÏß³ÌÍê³É¡£×îºó£¬ÎÒÃÇÊä³öÒ»ÌõÐÂÎÅÀ´ÌåÏÖÖ÷Ï̡߳£
½ÓÏÂÀ´£¬ÎÒÃǽ¨ÉèÒ»¸öÃûΪ”CMakeLists.txt”µÄÎļþ£¬²¢ÔÚÆäÖбàдÒÔÏÂÄÚÈÝ£º
cmake_minimum_required(VERSION 3.12) project(Threads) set(CMAKE_CXX_STANDARD 14) find_package(Threads REQUIRED) add_executable(Threads main.cpp) target_link_libraries(Threads PRIVATE Threads::Threads)
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýµÄCMakeLists.txtÎļþÖУ¬ÎÒÃÇÊ×ÏÈÖ¸¶¨ÁËCMakeµÄ×îµÍ°æ±¾ÒªÇó¡£È»ºó£¬ÎÒÃÇÉèÖÃÁËC++±ê×¼µÄ°æ±¾ÎªC++14¡£
½Ó×Å£¬ÎÒÃÇʹÓÃfind_packageÏÂÁîÀ´²éÕÒThreads¿â¡£Õâ¸ö¿âÊÇC++±ê×¼¿âµÄÒ»²¿·Ö£¬ÆäÖаüÀ¨Á˶àÏß³ÌÏà¹ØµÄ¹¦Ð§¡£ÎÒÃÇͨ¹ýREQUIREDÒªº¦×Ö¸æËßCMakeÕâÊDZØÐèµÄ¡£
È»ºó£¬ÎÒÃÇʹÓÃadd_executableÏÂÁîÀ´Ö¸¶¨ÒªÌìÉúµÄ¿ÉÖ´ÐÐÎļþµÄÃû³ÆºÍÔ´Îļþ¡£ÔÚÕâ¸öÀý×ÓÖУ¬ÎÒÃǽ«ÌìÉúÒ»¸öÃûΪ”Threads”µÄ¿ÉÖ´ÐÐÎļþ£¬²¢Ê¹ÓÔmain.cpp”×÷ΪԴÎļþ¡£
×îºó£¬ÎÒÃÇʹÓÃtarget_link_librariesÏÂÁThreads¿âÁ´½Óµ½×ðÁú¿Ê±¿ÉÖ´ÐÐÎļþÉÏ¡£
ÏÖÔÚ£¬ÎÒÃÇ¿ÉÒÔʹÓÃÒÔÏÂÏÂÁîÀ´¹¹½¨×ðÁú¿Ê±Ó¦ÓóÌÐò£º
mkdir build cd build cmake .. make
µÇ¼ºó¸´ÖÆ
ÕâЩÏÂÁÔÚ”build”Ŀ¼ÏÂÌìÉúÏîÄ¿Îļþ£¬²¢¹¹½¨¿ÉÖ´ÐÐÎļþ¡£
Íê³Éºó£¬ÎÒÃÇ¿ÉÒÔÔËÐÐ×ðÁú¿Ê±Ó¦ÓóÌÐò£º
./Threads
µÇ¼ºó¸´ÖÆ
Äú½«¿´µ½ÀàËÆÒÔϵÄÊä³ö£º
This is a thread. This is the main thread.
µÇ¼ºó¸´ÖÆ
ÖÁ´Ë£¬ÎÒÃÇÀֳɵØʹÓÃCMakeÉèÖú͹¹½¨ÁËÒ»¸ö¼òÆӵĶàÏß³ÌÓ¦ÓóÌÐò¡£
×ܽáÆðÀ´£¬Ê¹ÓÃCMakeÉèÖú͹¹½¨Linux¶àÏß³ÌÓ¦ÓóÌÐòÏà¶Ô¼òÆÓºÍÀû±ã¡£¿ÉÒÔͨ¹ý±àдCMakeLists.txtÎļþÀ´Ö¸¶¨ÒÀÀµÏîºÍÁ´½Ó¿â£¬²¢Ê¹ÓÃÏìÓ¦µÄÏÂÁîÀ´ÌìÉú¿ÉÖ´ÐÐÎļþ¡£Ç¿Ê¢µÄCMake¹¤¾ß¿ÉÒÔ´ó´ó¼ò»¯ÏîÄ¿µÄ¹¹½¨Àú³Ì¡£
Ï£Íû±¾ÎĵÄʾÀý´úÂëºÍ˵Ã÷Äܹ»×ÊÖúÄú¸üºÃµØÃ÷È·ÔõÑùʹÓÃCMake¹¹½¨¶àÏß³ÌÓ¦ÓóÌÐò¡£×£ÄãÔÚLinux¿ª·¢ÖÐÈ¡µÃÀֳɣ¡
ÒÔÉϾÍÊÇʹÓÃCMake¹¹½¨Linux¶àÏß³ÌÓ¦ÓóÌÐòµÄÉèÖü¼ÇɵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡