compiling cpp code includes PETSc with Cmake

1.4k Views Asked by At

I want to use PETSc in a cpp code. I installed PETScand when run the cmd echo $PETSC_DIRI got the path to the library. I make a hello world code and

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

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

and the CMakeLists.txtis as follows:

cmake_minimum_required(VERSION 3.20.3)
project(ddm_library)

include_directories(include)

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

add_executable(main ${SOURCES})

and run following cmds

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

When I run the last cmd I got the following error

/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

Where did I make a mistake?

1

There are 1 best solutions below

0
On

I changed CMakeLists.txt and use find_package(PkgConfig), now it works. The final version of CMakeLists.txt is like this

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})