Home > Net >  CMake isn't able to include header file into my source file
CMake isn't able to include header file into my source file

Time:06-19

I'm learning CMake and got to the part where I learn how to include header files. The problem is that I get an error, saying that the header file has not been found.

I'm on Windows 10, by the way.

All I have as of right now is a src and include directories along with the CMakeLists.txt file. In source, I only have a single file and I also only have a single file in include. This is my main.cpp file:

#include <iostream>
#include "include/main.h"
int main() {
    std::cout << "Hello, World!\n";
    sayHi("Joshua");
    return 0;
}

And this is my CMakeLists.txt file.

cmake_minimum_required(VERSION 3.10)
set(CXX_STANDARD 17)
set(CXX_STANDARD_REQUIRED ON)
project(hello VERSION 1.0)
add_executable(hello ../src/main.cpp)
target_include_directories(hello PUBLIC ${CMAKE_CURRENT_SRC_DIR}/include)

EDIT: I fixed the source code so that I includes main.h, rather than include/main.h, but I still end up with the same error:

"C:\Users\HP\desktop\test\4\build\hello.sln" (destino padrão) (1) ->
"C:\Users\HP\desktop\test\4\build\hello.vcxproj.metaproj" (destino padrão) (3) ->
"C:\Users\HP\desktop\test\4\build\hello.vcxproj" (destino padrão) (4) ->
(ClCompile destino) ->
  C:\Users\HP\Desktop\test\4\src\main.cpp(3,10): fatal error C1083: Cannot open include file: 'main.h
': No such file or directory [C:\Users\HP\desktop\test\4\build\hello.vcxproj]

    0 Aviso(s)
    1 Erro(s)
    ```

What is going on?

CodePudding user response:

It's ${CMAKE_CURRENT_SOURCE_DIR}, not ${CMAKE_CURRENT_SRC_DIR}.

If you fix this then the compiler should see the correct include directory.

At the moment because the variable doesn't exist, the only directory it sees is /include which is not what you want.

  • Related