0

I have seen that whether or not I add header files to add_library() I have to explicitly add the library forlder (using target_include_directories) in addition to linking the library (target_link_libraries())

For a MRE

/CMakeLists.txt
/main.cpp
/lib
  /CMakeLists.txt
  /lib.h
  /lib.cpp

# /CMakeLists.txt

cmake_minimum_required(VERSION 3.18)
project(Project)

add_executable(Exec main.cpp)
add_subdirectory(lib)

target_link_libraries(Exec PRIVATE
  Lib
)
target_include_directories(Exec PRIVATE
  "${PROJECT_SOURCE_DIR}/lib"
)
// /main.cpp

#include <iostream>
#include <lib.h>

int main() {

  std::cout << lib() << std::endl;
  return 0;
}
# /lib/CMakeLists.txt

add_library(Lib lib.cpp)
// /lib/lib.h

#ifndef LIB_H
#define LIB_H

const char * lib();

#endif /*LIB_H*/

// /lib/lib.cpp

const char * lib() {
  return "Hi World";
}

The code compiles and runs whether or not I add lib.h at the add_library() statement inside /lib/CMakeLists.txt, but in any case I have to add the lib directory using target_include_directories() Otherwise the compiler says

/main.cpp:2:10: fatal error: lib.h: No such file or directory

However I have seen many people adding header files at add_library() statements What can be their purpose?

Matias Haeussler
  • 953
  • 2
  • 11
  • 23
  • 3
    ***Why would I add *.h to add_library()?*** If you add the .h files they show up in Solution Explorer of Visual Studio as a header file that is part of your project. If you don't add it the IDE treats the header in a different manner making navigation in the IDE more difficult. – drescherjm Nov 09 '21 at 21:13

0 Answers0