Useful gcc parameters: ‘-I’ Include Folder
First I don’t like project that has all files in one folder with the compiled object files, libraries and binaries. Best thing to do is create folders based on categories, like ‘obj’ folder for all compiled objects, ‘lib’ folder for all shared libraries created. Its even better to organize your code in folders so that one can easily understand the structure of your project even without looking at the code.
First problem the newbies find in putting different files in different folders and then linking with files in other folder, etc.. gcc has a parameter passed while compiling ‘-I[folder-name]’ which automatically include the given folder to search for included files while compiling.
Lets take an example, We have two folders ‘include’ and ’src’ in ‘Proj’ folder.
File: debug.h in Folder ‘include’
#ifndef DEBUG_H_
#define DEBUG_H_
#include
void log_err(int errno)
{
fprintf(stderr, “Error No:%d\n”,errno);
return;
}
#endif
File: test.c in Folder ’src’
#include "debug.h"
int main()
{
log_err(10);
return 0;
}
Now when you try to compile ‘test.c’ from root ‘Project’ folder, with simple commad as follows:
$Project> gcc src/test.c -o test
It will give you following error:
src/test.c:1:19: error: debug.h: No such file or directory
To resolve this, there are two ways:
First, use folder name in including header file, like:
#include "include/debug.h"
But the problem in this method is, files are now fixed and also the compilation place is fixed. If ‘debug.h’ files needs to be moved to other folder, you need to change the ‘test.c’ file also.
Second, and better way is to use ‘-I’ flag of gcc to give the folder to include during compilation. In this method there is no need to change the code in ‘test.c’ or the ‘debug.h’ files. New compilation command would be:
$Project> gcc -Iinclude src/test.c -o test
This will successfully compile the test.c file and will generate the ‘test’ binary file. Using ‘-I’ argument, we can make change the files from one folder to other and only change the compilation flags to compile the project.
Normally we use ‘make’ to handle compilations of c/c++ based projects. Sometimes we also need to make some file mobile with respect to ‘make’. In other words, you want ‘make’ to find the file from different folders of project and you dont want to manually specify folder name with each file name.
In this situation, ‘VPATH’ internal variable of ‘make’ is useful. Like ‘-I’ in gcc, ‘VPATH’ includes folders in ‘make’ ’s search path to find the required file. It is used as follows:
VPATH:=include:src
Well, this gives you some basic ideas of making your code more mobile to compiling process.