3

For example:

project/utility/a.cpp

and

project/utility/a.h

are implementation file and header file for a batch of functions that are used everywhere in this project.

Now, imagine

project/component/b.h

would like to include a.h. A common solution is to use:

#include "../utility/a.h"

in b.h.

But this is not allowed in Google C++ style:

All of a project's header files should be listed as descendants of the project's source directory without use of UNIX directory shortcuts . (the current directory) or .. (the parent directory).

I tried to include it as showed in the document above, but it does not work.

So what should I do to include it without using '.' or '..' ?

Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
matrixit
  • 314
  • 3
  • 10

3 Answers3

7

See also What are the benefits of a relative path such as "../include/header.h" for a header? and Should I use #include in headers?

You need to decide on whether to use just the base name of the header file (a.h in your question's abbreviated example), or whether to use a subdirectory plus header name project/a.h). Either is workable as long as the header names are unique; the subdirectory version is often better and requires fewer command line options, in general.

You can write:

#ifndef B_H_INCLUDED
#define B_H_INCLUDED

#include "utility/a.h"

…other material required…

#endif /* B_H_INCLUDED */

and then, on the compiler command line, include an option:

-I ..

This ensures that the compiler will find utility/a.h as ../utility/a.h (unless there's a name conflict somewhere). Or you can specify the absolute path to your project:

-I /path/to/project

which will read /path/to/project/utility/a.h.

Community
  • 1
  • 1
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
5

So what should I do to include it without using '.' or '..' ?

You specify a path to the top include directory using the -I option of the compiler.

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
1

Normally, you should use Makefile or better to use automake. Since you are using C++, your make file simply add the header path to the CXXFLAGS variable.

----- your make file ----- Makefile:

CXXFLAGS += -I../utility
VPATH = ../utility

yourprog : b.o 
    $(CXX) $(CXXFLAGS) -o $@ $^ ../utility/a.o

In your source file, you only need to

#include "a.h"

In the Makefile, it is better to also add LDFLAGS. This segment of the Makefile is only showing the relevant part. A complete Makefile has many more lines of code. the -I compiler option tells the compiler to find herder files in the directory. You can have multiple -I options for the compiler. This is similar to the PATH variable in unix where your search path is separated by ":"

Kemin Zhou
  • 6,264
  • 2
  • 48
  • 56