Search code examples
c++c++17includeclioninclude-path

How do I include a .h file, located in an upper level directory? С++


So, for instance I have a bunch of files:

root-dir:
  dir-a:
    read.cpp
  dir-b:
    code.cpp
  lib.cpp
  lib.h

lib's files:

//lib.cpp

#include <string>
using namespace std;

string edit(string in) {
    string out;
    /*function body*/
    return out;
}
//lib.h

#include <string>
std::string edit(std::string in);

I need to include lib's function in both "read.cpp" and "code.cpp".

I tried to:

  • #include "lib.cpp" from both files, but it failed: fatal error: lib.cpp: No such file or directory

  • #include "lib.h" . Same: fatal error: lib.h: No such file or directory

  • #include "root-dir/lib.h", it highlights red: 'root-dir/lib.h' file not found

Obviously, #include "C:/.../.../root-dir/lib.h" is not a proper solution.


Solution

  • You can include lib.cpp by writing #include "../lib.cpp" here, but there are a few things to note:

    • You should always include header files, not source files.

    • A better approach would be to organize header and source files in separate folders. Here is an example:

      .
      ├── inc
      │   └── lib.h
      └── src
          ├── code.cpp
          ├── lib.cpp
          └── read.cpp