0
votes

I'm facing difficulty in understanding source and header files stuff. Suppose

1)I have a source file(functions.cpp) which contains function named 'int add(int x,int y)' in the location /Users/xyz/Desktop/functions.cpp.

2)The header file(functions.h) which contain the declaration of the functions in source file(functions.cpp) is placed in /Users/xyz/Documents/function.h

3)Other source file(main.cpp) which contain 'main()' function need to call the 'add()' function defined in 'functions.cpp'.The source file 'main.cpp' is located in /Users/xyz/Downloads/main.cpp

I'm placing these files in different locations so that i can understand these concepts better.

So,how do i link function.cpp to main.cpp using functions.h.

   #include "   "

What is the path that i should use in the above include?

Also,it is my understanding that .h files provides the declaration of functions which are defined some where else and having a declaration is necessary for the compiler to call the functions which are defined in some other files or functions which are not defined yet. Is that right? Please correct me in case I'm wrong.

5

5 Answers

5
votes
#include "functions.h"

Your code should not know about how you choose to arrange your source tree. To hard-code paths is to earn the hatred of whoever has to maintain this code (and that includes you six months from now).

Your build system -- whatever it is -- can deal with the paths. That could be as simple as:

g++ -I/Users/xyz/Documents -c functions.cpp

Your statement of how declarations/definitions work is basically correct.

3
votes

Your first question has no answer. C++ does not define how header files are found, it's up to the compiler and they all do it a bit differently. If you want an answer you'll have to look up the details in the documentation of your compiler. I would recommend you put everything the same directory and stop worrying about it.

In the second part of your question, your understanding seems pretty good to me.

0
votes

You should include in your main the exact path to your header file:

#include "/Users/xyz/Documents/function.h"

Hope this help.

Regards.

0
votes

You include functions.h in functions.cpp and main.cpp using #include then you compile both main.cpp and functions.cpp. The linker then links the two resulting object files. Your inclusion of functions.h in main.cpp will allow you to call the functions from functions.h within your main.cpp file

As for paths of files, provided that you specify to your compiler the required paths in which to find your code you should be fine.

0
votes

You can either use a full path

#include "/Users/xyz/Documents/function.h"

or a relative path (which is usually more preferable)

#include "../Documents/function.h"

Don't forget to specify full or relative paths to your .obj files when you are linking the final executable as well ;)