Reputation: 4928
I'm somewhat confused on how to add header files to C++ projects. Often times when I attempt to use a #include "genericheader.h", it says that the file can not be found. However, the file generally exists, it's simply that the path is not written correctly So my question, by using the #include "genericheader.h", where does the compiler look for this file? Does it look in the current directory of the file that is trying to include it? Or is it dependent on things such as the IDE?
If I'm trying to include a header file, is it generally best practice to have it placed within the directory of the current file trying to include it?
Apologies for the noobish question. Thanks!
Upvotes: 21
Views: 88207
Reputation: 1574
The order for searches has been explained very well, here I will explain how to tell the compiler to search under certain directories.
Suppose you are using bash
, then in ~/.bashrc
, write
C_INCLUDE_PATH="/full/path/to/your/file/:$C_INCLUDE_PATH" ## for C compiler
CPLUS_INCLUDE_PATH="/full/path/to/your/file/:$CPLUS_INCLUDE_PATH" ## for Cpp compiler
export C_INCLUDE_PATH
export CPLUS_INCLUDE_PATH
and source it with source ~/.bashrc
.
You should be good to go.
One thing to be notice is that, if you have
#include "abc/xxx.h"
int main()
{
return 0;
}
then your full path should not have abc
.
Upvotes: 8
Reputation: 2446
There two types of headers. Headers that are in the compilers library and headers that are in your project. Whether you use <>
or ""
tells the compiler where to look for the header file. However the compiler will not be unable to find them if you only use <>
. Bottom example shows how it works:
#include <iostream> // library header
#include "helloWorld.h" //header in project
#include "../helloworld/headers/helloworld.h" //path to header in project
#include </path/to/custom/header/headerFile.h>
using namespace std;
int main()
{
cout << "Hello World" << endl;
return 0;
}
Upvotes: 3
Reputation: 2946
If you use #include "genericheader.h"
, you should place the file genericheader.h
in current directory.
Look here for more information.
Upvotes: 1
Reputation: 590
You are using quoted form of include directive, it searches for include files in this order:
Further reading: https://msdn.microsoft.com/en-us/library/36k2cdd4.aspx
Upvotes: 11