Adding an external library to my project

Hi,

I am new to cmake and am trying to build my fortran project with an external library that has been added as a git submodule to my project repository. The external project has a CMakeLists.txt file and can be built using CMake. However, I am having hard time trying to build my project with it.

....
include_directories(${CMAKE_SOURCE_DIR}/external/{package}/include)

add_executable(myproject ${SUBROUTINES} ${MODULES} ${libraries})

# Link to the library

target_link_libraries(myproject PUBLIC package)

# Link libraries

# target_link_libraries(myprojtect ${libraries} package)

set(EXECUTABLE_OUTPUT_PATH ${CMAKE_SOURCE_DIR}/bin)

I use simple use {package} in my fortran code to reference the package. However, when I try to build with CMake I get the following error:

~/myproject/src/mymodule.f90(4): error #7002: Error in opening the compiled module file.  Check INCLUDE paths.

The usual thing to do is to use add_subdirectory for the project you’ve brought in as a git submodule. Did you try that?

I did but even then my target compilation fails as the module in my project is not ablet find the external package. How do I link my target explicitly with an external library compiled with cmake?

If you’ve done add_subdirectory then the external library should have been defined as a target in CMake and you use target_link_libraries to make your target link against the external library.

Did you do that?

I am sorry, but I am not sure where to define it as a target in my library’s CMake file?

The CMakeLists.txt in the external library creates targets, just like you do, with add_library.

Look at the other library’s CMakeLists.txt and find where it adds the library and use that target name to link against.

I tried this but CMake still doesn’t seem to recognize the library and shows an undefined reference error in my fortran module where I call it.

Post a link to the library you’re trying to use with add_subdirectory

Here’s the link to the library: GitHub - stenczelt/libmace

The interface code in my Fortran project is similar the examples/main.f90 in the above repo.

Looks to me like this is the target you want, since you said you are building Fortran:

I tried this and I still get an undefind reference error. I tried to link the target of my library with the above target and didn’t work.