Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

c/c++ relative include paths vs Makefile include flags

In a large project that has files structured in a directory tree structure, is it better to include relative path in source file, or just include header file and instruct compiler via Makefile where to find it?
Is there a preferred way?

Example:

#include "../path/to/file.h"  

vs.

#include "file.h"
gcc -I../path/to  

I believe that first case may be more readable while second approach would give ability to seamlessly move files...

like image 564
kometonja Avatar asked Aug 20 '15 12:08

kometonja


2 Answers

The second method is more efficient since you don't have to rewrite the path every single time you want to use this file.

Let's take an example.

You want to build a library containing some useful functions. Then you work on a project on which you need some of the library's functions, not all of them. So you choose to mv some on those files into your project folder.

This way, the path might not be the same, and you won't have to rewrite everything if you choose to include the path in the Makefile.

Coding your Makefile properly, let you have several $(PATH), which is very useful when working on big projects requiring multiple binaries for example.

I'm trying to be as clear as possible, but I really think, in my opinion, that the Makefile is a very powerful tool which can be used to his best to make the project development easier.

like image 197
Xcrowzz Avatar answered Sep 21 '22 18:09

Xcrowzz


It depends. For include files inside your project, giving the relative path can be useful, as the sub-directory is another structure-element and you do not have to care about equal file-names (mostly for C++, as C does not support custom-namespaces).

For external paths (e.g. other projects), you should definitively use the second method. Possibly just to the root of that structure. Similar to asm/byteorder.h.

In any way, if using explicit paths (in the source files), you should make sure they are well-documented and any change is tracked to the source files. (There are often common sub-directories, like config, etc. which will not change).

One strong recommendation: always use the project root as working directory. All explicit relative paths are from this root. That way you can avoid the problemativ parent (..) path.

Ultimative rule is not to use explicit paths which cross the project-root.

However, there is no other general rule. The actual layout is often subject to personal preferences. If the directory structure is well-thought, I'd prefer explicit paths.

like image 31
too honest for this site Avatar answered Sep 21 '22 18:09

too honest for this site