I'm new to this. I use Linux and gcc in bash .

There is:

  • p1.c:

    int func() { return 1889; } 
  • func.h:

     #ifndef ONCE #define ONCE int func(); #endif 
  • p2.c:

     #include <stdio.h> #include <func.h> int main() { int a = func(); printf("%d",a); return 0; } 

func.h I specifically moved to another folder. In *.bashrc* added export PATH="$PATH:/root/deleteme/spec"

 # echo $PATH /usr/local/sbin:/usr/local/bin:/usr/bin:/usr/lib/jvm/default/bin:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl:/root/deleteme/spec 

 # gcc p?.c 

conclusion:

 p2.c:2:18: fatal error: func.h: No such file or directory #include <func.h> ^ compilation terminated. 

Earned by specifying gcc -I .

Why doesn't it work through the environment variable? I want to figure out how it works. Thank :)

    1 answer 1

    The $PATH environment variable, which contains paths where executable files (scripts, programs) are located, has nothing to do with paths in which gcc searches for header files ( *.h ).

    There are default directories such as /usr/include , for example, used for libraries installed from *-dev system packages.

    A common way to specify your path to header files is to use the -I option. If you want, you can define the corresponding environment variables ( CPATH , etc) . If you use "func.h" instead of <func.h> , then func.h first searched in the directory with the current file ( p2.c ). There are other (less used) options that control how the headers are searched .

    • CPATH asked (via bash, right?), Gcc swears anyway - Mike AJ
    • 2
      @MikeAJ, correct what you wrote in .bashrc , replacing PATH with CPATH , and restart the shell session. if the variable is exported, you can check, for example, like this: echo $CPATH . // it is not necessary to perform user tasks from under an administrative account ( root ). - aleksandr barakin
    • Thanks, it works. How does CPATH differ from C_INCLUDE_PATH ? - Mike AJ
    • @MikeAJ: I would not use environment variables at all, but I would set the necessary -I options in the Makefile (or IDE, etc). Otherwise, when compiling someone else's code, you will have to worry if your headers conflict with this code (where the “someone else's code” may even be your own code, but after six months, when the details of the current project are already forgotten). - jfs
    • Ok, thank you. And why write #include "func.h" right at the very p1.c After all, this include here is not necessary? - Mike AJ