3

I have few header files in /my/path/to/file folder. I know how to include these files in new C program but everytime I need to type full path to header file before including it. Can I set some path variable in linux such that it automatically looks for header files ?

username_4567
  • 4,737
  • 12
  • 56
  • 92

3 Answers3

5

You could create a makefile. A minimal example would be:

INC_PATH=/my/path/to/file
CFLAGS=-I$(INC_PATH)

all:
    gcc $(CFLAGS) -o prog src1.c src2.c

From here you could improve this makefile in many ways. The most important, probably, would be to state compilation dependencies (so only modified files are recompiled).

As a reference, here you have a link to the GNU make documentation.

If you do not want to use makefiles, you can always set an environment variable to make it easier to type the compilation command:

export MY_INC_PATH=/my/path/to/file

Then you could compile your program like:

gcc -I${MY_INC_PATH} -o prog src1.c src2.c ...

You may want to define MY_INC_PATH variable in the file .bashrc, or probably better, create a file in a handy place containing the variable definition. Then, you could use source to set that variable in the current shell:

source env.sh

I think, however, that using a makefile is a much preferable approach.

betabandido
  • 18,946
  • 11
  • 62
  • 76
  • Thanks but is there any way without writing makefile? – username_4567 Jul 17 '12 at 10:08
  • @username_4567 I was just updating my question to include an alternative solution. But writing a 5 lines makefile seems to me like an easy and better solution. – betabandido Jul 17 '12 at 10:13
  • Thanks actually I thought there is be default path where all header files are looked for.. – username_4567 Jul 17 '12 at 10:15
  • @username_4567 There are some default paths (such as /usr/include). Options `-I` and `-L` let you use custom include and library paths. Of course, you do not want to type the long path all the time, so you need some kind of solution like the ones I mentioned :) – betabandido Jul 17 '12 at 10:18
3

there is a similar question and likely better solved (if you are interested in a permanent solution): https://stackoverflow.com/a/558819/1408096

Try setting C_INCLUDE_PATH (for C header files) or CPLUS_INCLUDE_PATH (for C++ header files).

Kudos:jcrossley3

Community
  • 1
  • 1
xhudik
  • 2,414
  • 1
  • 21
  • 39
1

I'm not in Linux right now and I can't be bothered to reboot to check if everything's right, but have you tried making symbolic links? For example, if you are on Ubuntu:

$ cd /usr/include
$ sudo ln -s /my/path/to/file mystuff

So then when you want to include stuf, you can use:

#include <mystuff/SpamFlavours.h>