0

I am trying to learn how to better organize a project and it's files in C++.

My simple test project only seems to work whenever main.cpp (and main.exe) is in the root project folder. Here's how I wanted to try to set it up.

  • Project
    • .vscode
      • c_cpp_properties.json
    • headers
      • header.h
    • main
      • main.cpp
      • main.exe

Inside of main.cpp, I have #include "headers/header.h"

When I try to compile it with this setup, I get this error fatal error: headers/header.h: No such file or directory

I am wondering why this doesn't work when the following setup, which doesn't have main.cpp in a subfolder, compiles and runs just fine (without changing any of the code).

  • Project
    • .vscode
      • c_cpp_properties.json
    • headers
      • header.h
    • main.cpp
    • main.exe

I am using Visual Studio Code with the C/C++ and C/C++ Compile Run extensions (in case that's relevant).

Edit:

Changing it to "../headers/header.h" does work, but I am wondering how I would do this without using ../.

If I'm understanding correctly I just need to add something to the includePath in c_cpp_properties.json. Here's what the "includePath" section looks like right now.

"includePath": [
    "${workspaceFolder}/**"
],

So I think I just need to make it something like

"includePath": [
    "${workspaceFolder}/**",
    "..."
],

What exactly should I be putting in the ... part?

Steven
  • 1
  • 1
  • 2
  • 1
    the compiler looks relative to the current file. Use `#include "../headers/header.h"` – rioV8 May 20 '20 at 08:16

1 Answers1

0

When compiling a specific file, your compiler will look at the path of this file. So, in your first example, it is .../Project/main/main.cpp, but in your second example it's ../Project/main.cpp. So now its obvious why looking at the path that is headers/header.h is valid in second case, but not the first one.

However, you can of course leave your main.cpp in your main directory if you wish, you'd only need to set INCLUDE_PATH directory. If you were using Makefile, it'd be a simple -I flag addition, but since you're using VS code, you might want to look at this question. Sorry I can't provide more detailed solution, I'm not really familiar with VS Code environment.

Rorschach
  • 734
  • 2
  • 7
  • 22