Linux Apps Tutorials - Herong's Tutorial Examples - v1.02, by Herong Yang
"g++ -I..." and CPATH Environment Variable
This section provides a tutorial example on how to use 'g++ -I...' option and/or CPATH environment variable to specify paths of include header files for GCC compiler.
If you are compiling a C/C++ program that uses custom header files, you need to specify the path name where the header files are located.
1. Create a simple header file, ./include/myheader.h:
herong$ vi ./include/myheader.h #define Name "herong"
2. Create a C++ program file that uses the header file:
herong$ vi HeaderTest.cpp #include "iostream" #include "string" #include "myheader.h" int main(void) { std::string who (Name); std::cout << "Hello " << who << "!" << std::endl; return 0; }
3. Compile it without specifying the include path:
herong$ g++ HeaderTest.cpp HeaderTest.cpp:3:10: fatal error: myheader.h: No such file or directory #include "myheader.h" ^~~~~~~~~~~~ compilation terminated.
4. Compile it with "-I ..." option to specify include path:
herong$ g++ -I ./include -v HeaderTest.cpp ... #include "..." search starts here: #include <...> search starts here: ./include /usr/include/c++/8 /usr/include/c++/8/x86_64-redhat-linux /usr/include/c++/8/backward /usr/lib/gcc/x86_64-redhat-linux/8/include /usr/local/include /usr/include End of search list. ... herong$ ./a.out Hello herong!
5. Compile it with "CPATH=..." environment variable to specify include path:
herong$ export CPATH=./include herong$ g++ -v HeaderTest.cpp ... #include "..." search starts here: #include <...> search starts here: ./include /usr/include/c++/8 /usr/include/c++/8/x86_64-redhat-linux /usr/include/c++/8/backward /usr/lib/gcc/x86_64-redhat-linux/8/include /usr/local/include /usr/include End of search list. ... herong$ ./a.out Hello herong!
Now I know the "-I ..." option or "CPATH" environment variable is adding more paths to the GCC default list to search for include header files.
Table of Contents
Running Apache Web Server (httpd) on Linux Systems
Running PHP Scripts on Linux Systems
Running MySQL Database Server on Linux Systems
Running Python Scripts on Linux Systems
Conda - Environment and Package Manager
"g++ --verbose" - GCC Compiler Steps and Settings
►"g++ -I..." and CPATH Environment Variable
"g++ -l..." to Link with Library Files
"g++ -c" and "ar src" to Build Static Library
"g++ -shared" to Build Dynamic Library
"ldd" - Dynamic Library Dependency Checker
"make" - Manage Program Build Process