编译 cpp 代码包括带有 Cmake 的 PETSc

问题描述

我想在 PETSc 代码中使用 cpp。我安装了 PETSc 并在运行 cmd echo $PETSC_DIR 时获得了库的路径。 我制作了一个你好世界代码和

#include "petsc.h"
#include <iostream>

int main()
{
   std::cout << "Hello Wold" << std:endl;
}

CMakeLists.txt 如下:

cmake_minimum_required(VERSION 3.20.3)
project(ddm_library)

include_directories(include)

file(GLOB SOURCES "src/*.cc")

add_executable(main ${SOURCES})

并运行以下 cmds

mkdir build
cd build
cmake CMAKE_INCLUDE_PATH=/opt/petsc/linux-c-opt/include ..
make

当我运行最后一个 cmd 时出现以下错误

/home/main.cc:5:10: fatal error: petsc.h: No such file or directory
    5 | #include "petsc.h"
      |          ^~~~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/main.dir/build.make:76: CMakeFiles/main.dir/src/main.cc.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:83: CMakeFiles/main.dir/all] Error 2
make: *** [Makefile:91: all] Error 2

我哪里做错了?

解决方法

我更改了 CMakeLists.txt 并使用了 find_package(PkgConfig),现在可以使用了。 CMakeLists.txt的最终版本是这样的

cmake_minimum_required(VERSION 3.20.3)


project(ddm_library)

# PkgConfig 
find_package(PkgConfig)

# PETSc
if (PKG_CONFIG_FOUND)
    pkg_check_modules(PETSC PETSc)
endif()

if (PETSC_FOUND)
    list(APPEND COMPILE_OPTIONS ${PETSC_CFLAGS})

    include_directories(${PETSC_INCLUDE_DIRS})
    
    set(LINK_FLAGS "${LINK_FLAGS} ${PETSC_LDFLAGS}")   
    
    list(APPEND LIBRARIES ${PETSC_LINK_LIBRARIES})   
    
    set(CMAKE_REQUIRED_FLAGS ${PETSC_CFLAGS})   
    
    set(CMAKE_REQUIRED_INCLUDES "${PETSC_INCLUDE_DIRS}")
endif()

include_directories(include )

file(GLOB SOURCES "src/*.cc")

add_executable(main ${SOURCES})

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...