在 macOS 上正确使用 omp.h 的方法

3
尝试在macOS上编译ASIFT算法的C++源代码时,我遇到了OpenMP库的问题。
编译器是Apple Clang,macOS版本为11.3。
首先,编译器告诉我找不到“omp.h”。我参考了this question并通过HomeBrew安装了libomp。在正确安装后,我更改了源文件中的以下代码:
#include "omp.h"

to:

#include "/usr/local/opt/libomp/include/omp.h"

这解决了之前的“未找到omp.h”错误。
但是,在执行make命令后,项目源代码仍无法正确编译。Clang会抛出链接器错误。终端输出如下:
Undefined symbols for architecture x86_64:
  "_omp_get_num_procs", referenced from:
      compute_asift_matches(int, int, int, int, int, int, int, std::__1::vector<std::__1::vector<std::__1::vector<keypoint, std::__1::allocator<keypoint> >, std::__1::allocator<std::__1::vector<keypoint, std::__1::allocator<keypoint> > > >, std::__1::allocator<std::__1::vector<std::__1::vector<keypoint, std::__1::allocator<keypoint> >, std::__1::allocator<std::__1::vector<keypoint, std::__1::allocator<keypoint> > > > > >&, std::__1::vector<std::__1::vector<std::__1::vector<keypoint, std::__1::allocator<keypoint> >, std::__1::allocator<std::__1::vector<keypoint, std::__1::allocator<keypoint> > > >, std::__1::allocator<std::__1::vector<std::__1::vector<keypoint, std::__1::allocator<keypoint> >, std::__1::allocator<std::__1::vector<keypoint, std::__1::allocator<keypoint> > > > > >&, std::__1::vector<std::__1::pair<keypoint, keypoint>, std::__1::allocator<std::__1::pair<keypoint, keypoint> > >&, siftPar&) in compute_asift_matches.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [demo_ASIFT] Error 1

我还在Xcode中编写了一个更简单的代码,只是为了测试。
#include "/usr/local/opt/libomp/include/omp.h"
#include <iostream>

int main()
{
    int num = omp_get_num_procs();
    std::cout<<num<<std::endl;
}

代码无法正确编译。
似乎编译器找不到在omp.h中声明的函数omp_get_num_procs()的实现。
以下是omp_get_num_procs()在omp.h中的声明(第69行):
extern int    __KAI_KMPC_CONVENTION  omp_get_num_procs    (void);

我不确定是编译器参数问题还是OpenMP没有正确安装。我已经确认libomp.alibomp.dylib已正确放置在/usr/local/opt/libomp/lib目录中。

请问有人能够提供一些关于这个问题的建议吗?谢谢。

2个回答

1

可能需要将libomp.a链接到项目中。这里提供了如何将静态库链接到Xcode C++项目的示例。


太好了!在将libomp.a链接到项目之后,无论是Xcode还是命令行Clang都能正常编译了。谢谢! - undefined

1
苹果编译器不支持OpenMP(至少在公开版本中)。缺少必要的头文件和库是有原因的!因此,最好安装一个支持OpenMP的编译器(使用brewmacPorts,这取决于您如何支持其他不来自Apple的工具)。回答您具体问题:“在macOS中正确使用omp.h的方法”,答案是“安装支持OpenMP的编译器”。

谢谢。通过HomeBrew安装的OpenMP库可以正常工作,而且在将libomp.a链接到项目后,Clang可以正确编译,正如@Borys在另一个答案中提到的那样。 - undefined
通常情况下,使用动态版本的libomp比静态链接llibomp.a更安全。(这样可以避免在与其他使用不同OpenMP编译器编译的库(例如某些BLAS库)进行链接时出现问题...) - undefined
谢谢您的建议!有机会的时候会进一步研究这个问题。 - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接