Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Which directories does include statement search in C/C++?

Tags:

c++

c

include

test.c:

#include "file.h"

In the above statement, which directories will be searched ?

I suppose the directory where test.c locates will be searched, right?

But is that all?

BTW, what's the benefit to use a header file? Java doesn't require a header file...

like image 899
user198729 Avatar asked Oct 30 '25 14:10

user198729


2 Answers

  • #include <header_name>: Standard include file: look in standard paths (system include paths setup for the compiler) first
  • #include "header_name": Look in current path first, then in include path (project specific lookup paths)

The benefit of using a header file is to provide others with the interface of your library, without the implementation. Java does not require it because java bytecode or jar is able to describe itself (reflexion). C code cannot (yet) do it.

In Java you would only need the jar and have the correct use statement. In C you will (mostly) need a header and a lib file (or header and dll).

The other reason is the way c code is compiled. The compiler compiles translation units (a c/cpp file with all included headers) and the linker in a second step links the whole stuff. Declarations must not be compiled, and this saves time and avoid code to be useless generated for each compilation unit which the linker would have to cleanup.

This is just a general idea, I am not a compiler specialist but should help a bit.

like image 137
jdehaan Avatar answered Nov 01 '25 05:11

jdehaan


It's controlled by your compiler. For example, gcc has a -I option to specify the include path.

C and C++ prototypes are required so the compiler (distinguished from the linker) can make sure functions are being called with the correct arguments. Java is different in that the compiler uses the binary .class files (which unlike C are in a standard bytecode format with all type information preserved) to check that calls are valid.

like image 23
Matthew Flaschen Avatar answered Nov 01 '25 03:11

Matthew Flaschen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!