ʹÓÃCMake¹¹½¨Linux²¢ÐÐÅÌËãÓ¦ÓóÌÐòµÄÉèÖü¼ÇÉ
ʹÓÃcmake¹¹½¨linux²¢ÐÐÅÌËãÓ¦ÓóÌÐòµÄÉèÖü¼ÇÉ
ÔÚLinuxϵͳÏ¿ª·¢²¢ÐÐÅÌËãÓ¦ÓóÌÐòÊÇÒ»ÏîºÜÊÇÖ÷ÒªµÄʹÃü¡£ÎªÁ˼ò»¯ÏîÄ¿µÄÖÎÀíºÍ¹¹½¨Àú³Ì£¬¿ª·¢Õß¿ÉÒÔÑ¡ÔñʹÓÃCMake×÷ΪÏîÄ¿¹¹½¨¹¤¾ß¡£CMakeÊÇÒ»¸ö¿çƽ̨µÄ¹¹½¨¹¤¾ß£¬¿ÉÒÔ×Ô¶¯ÌìÉú²¢ÖÎÀíÏîÄ¿µÄ¹¹½¨Àú³Ì¡£±¾ÎĽ«ÏÈÈÝʹÓÃCMake¹¹½¨Linux²¢ÐÐÅÌËãÓ¦ÓóÌÐòµÄһЩÉèÖü¼ÇÉ£¬²¢¸½ÉÏ´úÂëʾÀý¡£
Ò»¡¢×°ÖÃCMake
Ê×ÏÈ£¬ÎÒÃÇÐèÒªÔÚLinuxϵͳÉÏ×°ÖÃCMake¡£¿ÉÒÔ´ÓCMakeµÄ¹Ù·½ÍøÕ¾ÏÂÔØ×îа汾µÄÔ´´úÂë²¢¾ÙÐбàÒë×°Öã¬Ò²¿ÉÒÔÖ±½ÓʹÓÃϵͳµÄ°ü¹ÜÀí¹¤¾ß¾ÙÐÐ×°Öá£ÏÂÃæÒÔUbuntuϵͳΪÀý£¬ÏÈÈÝÔõÑùʹÓðü¹ÜÀí¹¤¾ß×°ÖÃCMake£º
sudo apt-get install cmake
µÇ¼ºó¸´ÖÆ
¶þ¡¢½¨ÉèCMakeLists.txt
ÔÚÏîÄ¿¸ùĿ¼Ï½¨ÉèÒ»¸öÃûΪCMakeLists.txtµÄÎļþ¡£Õâ¸öÎļþÊÇCMakeµÄÉèÖÃÎļþ£¬ÓÃÓÚ¸æËßCMakeÔõÑù¹¹½¨ÏîÄ¿¡£ÒÔÏÂÊÇÒ»¸ö¼òÆÓµÄCMakeLists.txtµÄʾÀý£º
cmake_minimum_required(VERSION 3.10) project(ParallelApp) find_package(OpenMP REQUIRED) set(CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++11 -fopenmp") set(SOURCE_FILES main.cpp) add_executable(ParallelApp ${SOURCE_FILES}) target_link_libraries(ParallelApp PRIVATE OpenMP::OpenMP_CXX)
µÇ¼ºó¸´ÖÆ
ÉÏÊöʾÀýÖУ¬ÎÒÃÇÊ×ÏÈÖ¸¶¨ÁËCMakeµÄ×îµÍ°æ±¾ºÅΪ3.10¡£È»ºó£¬Í¨¹ýfind_packageÏÂÁî²éÕÒOpenMP¿â¡£OpenMPÊÇÒ»ÖÖ²¢ÐÐÅÌËãµÄ±ê×¼£¬¿ÉÒÔÓÃÓÚÔÚ¶àºË´¦ÀíÆ÷ÉϾÙÐв¢Ðл¯²Ù×÷¡£½ÓÏÂÀ´£¬ÎÒÃÇÉèÖÃÁ˱àÒë±ê¼Ç£¨CMAKE_CXX_FLAGS£©ÎªC++11°æ±¾ºÍOpenMPÖ§³Ö¡£È»ºó£¬Ö¸¶¨ÁËÏîÄ¿Ô´Îļþ£¨SOURCE_FILES£©µÄÃû³ÆΪmain.cpp¡£×îºó£¬Ê¹ÓÃadd_executableÏÂÁÉèÒ»¸öÃûΪParallelAppµÄ¿ÉÖ´ÐÐÎļþ£¬²¢Ê¹ÓÃtarget_link_librariesÏÂÁOpenMP¿âÁ´½Óµ½¿ÉÖ´ÐÐÎļþÖС£
Èý¡¢±àÒëºÍÔËÐÐÏîÄ¿
ÔÚÏîÄ¿¸ùĿ¼Ï·¿ªÖնˣ¬Ö´ÐÐÒÔÏÂÏÂÁî±àÒëÏîÄ¿£º
mkdir build cd build cmake .. make
µÇ¼ºó¸´ÖÆ
ÉÏÊöÏÂÁÔÚbuildĿ¼ÏÂÌìÉú¿ÉÖ´ÐÐÎļþParallelApp¡£ÒªÔËÐÐÏîÄ¿£¬¿ÉÒÔÖ´ÐÐÒÔÏÂÏÂÁ
./ParallelApp
µÇ¼ºó¸´ÖÆ
ËÄ¡¢´úÂëʾÀý
ÏÂÃæÊÇÒ»¸ö¼òÆÓµÄʹÓÃOpenMP²¢ÐÐÅÌËãµÄC++´úÂëʾÀý£º
#include <iostream> #include <omp.h> int main() { int num_threads = omp_get_max_threads(); int sum = 0; #pragma omp parallel for reduction(+:sum) for(int i = 0; i < 100; i++) { sum += i; } std::cout << "Sum: " << sum << std::endl; return 0; }
µÇ¼ºó¸´ÖÆ
ÔÚÕâ¸öʾÀýÖУ¬ÎÒÃÇʹÓÃÁËOpenMPµÄ²¢Ðл¯Ö¸Áî#pragma omp parallel for£¬ÒÔ¼°reductionÖ¸ÁîÀ´ÇóÈ¡iµÄ×ܺ͡£ÔÚ±àÒëºÍÔËÐÐÕâ¸öʾÀý֮ǰ£¬ÐèҪȷ±£ÏµÍ³ÉÏÒѾװÖÃÁËOpenMP¿â¡£
ͨ¹ýÒÔÉϵÄÉèÖã¬ÎÒÃÇ¿ÉÒÔÇáËɵØʹÓÃCMake¹¹½¨²¢ÐÐÅÌËãÓ¦ÓóÌÐò£¬²¢ÔÚLinuxϵͳÉϾÙÐбàÒëºÍÔËÐС£CMakeÌṩÁ˸»ºñµÄÉèÖÃÑ¡ÏîºÍÎÞаµÄÀ©Õ¹ÐÔ£¬Àû±ã¿ª·¢Õßƾ֤×Ô¼ºµÄÐèÇó¾ÙÐÐÏîÄ¿µÄÉèÖú͹¹½¨¡£
×ܽá
±¾ÎÄÏÈÈÝÁËʹÓÃcmake¹¹½¨linux²¢ÐÐÅÌËãÓ¦ÓóÌÐòµÄÉèÖü¼ÇÉ£¬²¢¸½ÉÏÁË´úÂëʾÀý¡£Í¨¹ýºÏÀíÉèÖÃCMakeLists.txtÎļþ£¬ÎÒÃÇ¿ÉÒÔÇáËɵØÖÎÀíºÍ¹¹½¨²¢ÐÐÅÌËãÏîÄ¿¡£Óë´Ëͬʱ£¬Ê¹ÓÃOpenMP²¢ÐÐÅÌËã¿â£¬ÎÒÃÇ¿ÉÒÔ³ä·ÖʹÓöàºË´¦ÀíÆ÷µÄÐÔÄÜ£¬Ìá¸ßÓ¦ÓóÌÐòµÄÅÌËãÐÔÄÜ¡£Ï£Íû±¾ÎĹØÓÚÕýÔÚ¿ª·¢Linux²¢ÐÐÅÌËãÓ¦ÓóÌÐòµÄ¿ª·¢ÕßÓÐËù×ÊÖú¡£
ÒÔÉϾÍÊÇʹÓÃCMake¹¹½¨Linux²¢ÐÐÅÌËãÓ¦ÓóÌÐòµÄÉèÖü¼ÇɵÄÏêϸÄÚÈÝ£¬¸ü¶àÇë¹Ø×¢±¾ÍøÄÚÆäËüÏà¹ØÎÄÕ£¡