-2

I am currently trying to figure out how to link libraries in CMake. To the best of my knowledge I have everything set up properly. However, when I try to build I get the following error.

test/src/test.cpp:1:10: fatal error: lib.h: No such file or directory
#include "lib.h"
         ^~~~~~~
compilation terminated.
make[2]: *** [CMakeFiles/a.out.dir/build.make:63: 
CMakeFiles/a.out.dir/src/test.cpp.o] Error 1
make[1]: *** [CMakeFiles/Makefile2:110: CMakeFiles/a.out.dir/all] Error 2
make: *** [Makefile:84: all] Error 2

My file structure is

CMakeLists.txt
\src
    test.cpp
    \lib
        lib.h
        lib.cpp

Here are my files

CMakeLists.txt:

cmake_minimum_required(VERSION 2.9 FATAL_ERROR)
project("test")

set(CMAKE_RUNTIME_OUTPUT_DIRECTORY ${CMAKE_BINARY_DIR}/bin)

add_library(lib STATIC src/lib/lib.cpp)

add_executable(a.out src/test.cpp )
target_link_libraries(a.out lib)

src/test.cpp:

#include "lib.h"

int main(){
    hello();
    return 0;
}

src/lib/lib.h

#include <iostream>

void hello();

and src/lib/lib.hpp

#include "lib.h"

void hello(){
    std::cout << "Hello World" << std::endl;
}

Unless I am mistaken, whenever you static link you do not have to

#include "path/to/file/file.h"

you can just

#include "file.h"
jww
  • 97,681
  • 90
  • 411
  • 885
Joe
  • 13
  • 2

2 Answers2

1

The directory containing your header is not in the include path; you can use

target_include_directories(a.out PUBLIC ${CMAKE_SOURCE_DIR}/src/lib)

to specify the path to be added to your binary compilation

See https://cmake.org/cmake/help/v3.0/command/target_include_directories.html for more details on the syntax.

OznOg
  • 4,440
  • 2
  • 26
  • 35
-1

Add to CMakeList.txt:

include_directories("./src/lib")
YaatSuka
  • 47
  • 6