3

I am about to start writing a code in C++ for my PhD. Until now I worked with small code. All the files (sources and headers) in one directory.

Since I want to write a more organized code, I'll put files in different directories.

So what is the proper way to include files? Should I use something like

#include "../../folder/file.hpp" 

It doesn't look very clean. And is the code portable to Windows if includes are done this way?

5
  • 3
    I would consider ../ in #includes as confusing, dangerous, and bad style. (I use it only in rare specific situations where nobody else can see it.) In general, for large projects with many source code files, stored in multiple sub-directories, I prefer a basic "overall" include directory (which is used as include path, compiler arg. -I) and #include paths relative to this. Commented Nov 26, 2019 at 12:31
  • 6
    Invest some time in setting up proper infrastructure for building. Something like CMake or Bazel will allow you to define subcomponents with their own compile flags and filesets and define how to connect these to the rest of your codebase. If done well you should never have to set up an include path by hand. As an example, see "it's time to do CMake right" and the Bazel C++ tutorial Commented Nov 26, 2019 at 12:32
  • 3
    Concerning Windows, /s in #includes are fine. Windows C++ compilers can read this as well, and, as you mentioned yourself, it's necessary to keep code portable. Commented Nov 26, 2019 at 12:33
  • Try it that way and see how you go (with the quotes in the right place). I tend to use directives like -I for library includes, and ".." etc for headers in my own project. But that's an opinion, and others may have other ideas. Commented Nov 26, 2019 at 12:38
  • As @Botje said, learn CMake or some sort of build system. If you find it overwhelming, I recommend looking into Clion. Clion is an IDEA designed for C/C++. It supports CMake and adds it to a new project. Start your project in Clion, and slowly find your way toward CMake and build system. Commented Nov 26, 2019 at 13:08

1 Answer 1

4

is the code portable to Windows

I don't see a reason why it wouldn't be, as long as you fix the syntax of the directive first. I don't have a windows to test at the moment, but that's a valid path.

However, I would recommend to avoid parent directory include paths. Instead, specify a directory as an include directory for the compiler, put all your headers there into sub-directories and include with a path relative to the include directory.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.