Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#include parent directory's file

Tags:

c++

include

cmake

My folder structure is

libA
    x.h
    y.h
    algorithm/
        a.h

Now in a.h I have #include "libA/x.h" which is not working. Its searching for algorithm/libA/x.h. So should I use #include "../x.h" ? Is the second option a bad design ? currently libA is header only. but latter I may choose to compile it as a library

I am using cmake So can I or Should I add libA in my include path ?

In short

some files in My algorithm directory needs to include definitions from its parent folder. I cannot make all functions templated because the types are obvious and it will be overdoing. So How should I design My project ?

like image 295
Dipro Sen Avatar asked Feb 27 '13 19:02

Dipro Sen


1 Answers

Your solution with #include "../x.h" will work. Regarding whether this is bad design - probably it is; hard to tell without knowing more about your code.

Consider the fact that if you have many include paths, the compiler/preprocessor will look for ../x.h is all of them, which may be unintended and too broad!

Suppose you have the following directory structure, and Your_Code is in a search path for include-files.

Unrelated_Directory/
    x.h - unrelated
    Your_Code/
        libA/
            x.h - the real one
            algorithm/
                a.h

This is dangerous. If you remove/rename your real x.h, the compiler will silently pick Your_Code/../x.h, which contains unrelated stuff - this can lead to cryptic error messages. Or even worse, this may be an old version, full of bugs!

like image 111
anatolyg Avatar answered Sep 19 '22 19:09

anatolyg