Viktor Zhou
Viktor Zhou

Reputation: 11

C++ Include Relative Paths Broken

I am currently working on a large-scale financial application.

There are multiple modules that are compiled separately and then combined in a higher-level makefile.

Due to poor design, a lot of the header files include lots of local includes.

My problem is, when I include /src/equity/pdeModels/EqUtil.H inside my current source file /src/rwBatch/calcVol.C, all the includes at the start of EqUtil.H start to break, giving an error: ../../equity/pdeModels/EqUtil.H:15:30: fatal error: ulbase/SpotPrice.H: No such file or directory compilation terminated.

rwBatch and the equity folder are separately compiled and linked together later. Is this a problem with the makefile? Or how should I go about resolving this?

Indepth example:

/src/Module1/file1.C
/src/Module2/folderA/file2.H
/src/Module2/folderB/file3.H

When I write #include "../folderA/file2.H" in file1.C there are errors because of file2.H.
At the start of file2.H there are several includes, for example #include "/folderB/file3.H" which, when compiled in file1.C leads to fatal error: /folderB/file3.H: No such file or directory compilation terminated.

Is this a problem with the makefile? Or how should I go about resolving this?

Upvotes: 0

Views: 2728

Answers (1)

Beta
Beta

Reputation: 99094

Specifying a path in an #include statement is almost always a bad idea. It takes information needed by the builder but not by the code, and locks it into the code.

As long as there are no name collisions (e.g. folderA/file3.h and folderB/file3.h) you can simply remove those paths. Change these:

// file1.c:
#include "../folderA/file2.H"

// file2.H:
#include "/folderB/file3.H"

to these:

// file1.c:
#include "file2.H"

// file2.H:
#include "file3.H"

And in your makefile (or other build system):

gcc -I/src/Module2/folderA -I/src/Module2/folderB -c /src/Module1/file1.C -o /wherever/file1.o

If there are name collisions, and you have a module that depends on two headers with the same name, you have some options. The simplest -- and probably best -- is to rename one or both of the headers. If you really must, you can put paths into the #include statements, but the paths should reflect the directory structure you use, not the other way around.

Upvotes: 1

Related Questions