1

I have following structure in my project.

project-
  include-
  src-
     ab.cpp
     ab.h
  tests
     CMakeLists.txt
  CMakeLists.txt

I create library in project/CMakeLists.txt directory using add_library. In tests directory CMake, I use target_link_libraries. Now my test.cpp it does not find ab.h I have to use target_include_directories with project/src path. Does the target_link_libraries only finds header from include directory or what I am missing here?

debonair
  • 2,505
  • 4
  • 33
  • 73
  • `target_link_libraries` only effects linker settings, it has nothing to do with adding extra include locations – user7860670 Apr 29 '20 at 21:48
  • Related: [https://stackoverflow.com/a/40244458/487892](https://stackoverflow.com/a/40244458/487892) – drescherjm Apr 29 '20 at 22:17
  • 1
    Rather than knowing only the structure of your project, it would be necessary to see your CMakeLists.txt files to give sound advise. – vre Apr 30 '20 at 06:29

1 Answers1

0

The actions necessary for linking are similar to regular flow of a C++ project.

For a project with this structure:

src
  A.cpp
  A.h
  B.cpp
  B.h

When code in B.cpp wants to use a function defined in A.h it needs to declare it with #include<A.h> statement, this way the code of A.h is copied by the preprocessor so the translation unit of B.cpp is aware of it's existence.

In the link stage all object files are linked - the "promise" you made by declaring all A.h declarations are fulfilled by A.o.

Similarly, when test.cpp uses a function from a library - you first need to declare it, this is why you should use target_include_directories and include ab.h in test.cpp.

Then, for the linking stage you should let the linker know where the implementation of those functions declared in ab.h are found (your static/dynamic library file), for this you use target_link_libraries.

joepol
  • 744
  • 6
  • 22