3

I have a set of includes that reside in a far off directory meaning that including them requires a long include, such as:

#include "../../Path/to/my/file.h"

Where I have multiple of these it becomes a bit inconvenient so I am thinking I may be able to use a #define for the directory path and then concat the file name that I need, i.e.

#define DIR "../../Path/to/my/"
#define FILE1 "file.h"
#define FILE2 "anotherFile.h"

#include DIR FILE1 // should end up same as line in first example after pre-proc

However this does not work... is there anyway to concatenate within the workings of the C pre-processor suitable for this?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Toby
  • 9,696
  • 16
  • 68
  • 132

2 Answers2

6

The compiler will do macro replacement on an #include line (per C 2011 [N1570] 6.10.2 4), but the semantics are not fully defined and cannot be used to concatenate file path components without additional assistance from the C implementation. So about all this allows you to do is some simple substitution that provides a complete path, such as:

#define MyPath "../../path/to/my/file.h"
#include MyPath

What you can do with most compilers and operating systems is:

  • Tell the compiler what directories to search for included files (as with GCC’s -I switch).
  • Create symbolic links to other directories, so that #include "FancyStuff/file.h" becomes equivalent to ../../path/to/FancyStuff because there is a symbolic link named FancyStuff that points to the longer path.
Antonio
  • 19,451
  • 13
  • 99
  • 197
Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
4

You can't customise the search path for include files like this, but you can tell the compiler where to look for include files. Many compilers -I option for that, e.g.:

gcc -c stuff.c -I/path/to/my/ -I/path/to/other/

If that makes your compilation command too long, you should write a Makefile or, if you are working in Visual Studio or similar IDE, customise the search path in your project settings.

M Oehm
  • 28,726
  • 3
  • 31
  • 42