之前一直不知道怎么配置clion下的cmakelist.txt导致程序运行不了, mac下的cmakelist跟linux还稍微有些区别
macos版本: Mojave 10.14.6
xcode 版本:11.3.1
clang版本: 11.0.0
首先确保已经安装openmp以及所需的工具
安装openmp可参考:https://iscinumpy.gitlab.io/post/omp-on-high-sierra/
进入clion后按command+,(逗号) 进入设置页面, 选择toolchains
- 将C Compiler的内容替换成/usr/bin/gcc
- 将C++ Compiler的内容替换成/usr/bin/g++
如果不设置c和c++的compiler Clion会自动找到苹果默认的compiler最终会导致编译不过, 这里不清楚具体的原因
有几点疑问不太清楚的
- 为何要加-Xpreprocessor? 根据那个安装openmp链接的解释, 似乎因为openmp不是作为Mac 的build-in包所以clang 本身不支持, 导致调用的时候需要添加-Xpreprocessor参数?
- 如果没有额外安装g++和gcc的前提下, xcode默认的g++和gcc实际是指向clang的, 这也是为什么网上找了很多参考别人用同样的cmakelist能成功而我一直编译不过的原因. 如果自行安装g++和gcc应该不需要-Xpreprocessor这个参数. 同时需要注意网上很多例子调用openmp是-fopenmp=libomp 但如果用clang的话就需要改成-fopenmp -lomp.
将cmakelist改成如下模样(ref:https://stackoverflow.com/a/48216682/7741358)
cmake_minimum_required(VERSION 3.6)
project(collrank)
set(CMAKE_C_COMPILER "/usr/bin/gcc") #这里写你的gcc路径
set(CMAKE_CXX_COMPILER "/usr/bin/g++") #这里写你的g++路径
set(OPENMP_LIBRARIES "/usr/local/libomp/lib") #这里写你的libomp路径, 通过brew安装的默认地址
set(OPENMP_INCLUDES "/usr/local/libomp/include")#这里写你的libomp路径
message("here")
message("${CMAKE_CXX_COMPILER}")
OPTION (USE_OpenMP "Use OpenMP to enamble <omp.h>" ON)
# Find OpenMP
if(APPLE AND USE_OpenMP)
if(CMAKE_C_COMPILER_ID MATCHES "Clang")
set(OpenMP_C "${CMAKE_C_COMPILER}")
set(OpenMP_C_FLAGS "-Xpreprocessor -fopenmp -lomp -Wno-unused-command-line-argument")
#注意以上需要增加-Xpreprocessor 以及不能直接-llibomp 在这里不需要前缀lib只需要-lomp即可,下面相似的地方也是同个道理
set(OpenMP_C_LIB_NAMES "libomp" "libgomp" "libiomp5")
set(OpenMP_libomp_LIBRARY ${OpenMP_C_LIB_NAMES})
set(OpenMP_libgomp_LIBRARY ${OpenMP_C_LIB_NAMES})
set(OpenMP_libiomp5_LIBRARY ${OpenMP_C_LIB_NAMES})
endif()
if(CMAKE_CXX_COMPILER_ID MATCHES "Clang")
set(OpenMP_CXX "${CMAKE_CXX_COMPILER}")
set(OpenMP_CXX_FLAGS "-Xpreprocessor -fopenmp -lomp -Wno-unused-command-line-argument")
set(OpenMP_CXX_LIB_NAMES "libomp" "libgomp" "libiomp5")
set(OpenMP_libomp_LIBRARY ${OpenMP_CXX_LIB_NAMES})
set(OpenMP_libgomp_LIBRARY ${OpenMP_CXX_LIB_NAMES})
set(OpenMP_libiomp5_LIBRARY ${OpenMP_CXX_LIB_NAMES})
endif()
endif()
if(USE_OpenMP)
find_package(OpenMP REQUIRED)
endif(USE_OpenMP)
if (OPENMP_FOUND)
include_directories("${OPENMP_INCLUDES}")
link_directories("${OPENMP_LIBRARIES}")
set (CMAKE_C_FLAGS "${CMAKE_C_FLAGS} ${OpenMP_C_FLAGS}")
set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} ${OpenMP_CXX_FLAGS}")
endif(OPENMP_FOUND)
add_executable(
abc
main.cpp
)