source and header files - c++

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.

#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.

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.

You should include in your main the exact path to your header file:
#include "/Users/xyz/Documents/function.h"
Hope this help.
Regards.

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.

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 ;)

Related

How to include different headers from different folders? [duplicate]

This question already has answers here:
What is the difference between #include <filename> and #include "filename"?
(30 answers)
Closed 7 years ago.
I have a C++ project and I love mycode organized, however when I put everything in separate directories (headers and source files kept together) I am not able to include headers from another folder.
For example: I have two classes called "FooException" and "ContentProvider", which obviously go into separate directories, FooException being an exception and ContentProvider being a utility. Of course, I put them into different folders, but when I try to include the FooException in the ContenProvider it does not work and says that it could not find the source file. Has anyone encountered such problem? Any suggestions?
Thanks in advance and Happy New Year!
UPD:
Okay, people suggested looking at the differences between #include <> and #include "" and that still did not help. Although I am able to access any files from my Main.cpp I am not able to access files neither in my ContentProvider class nor in FooException class no matter which #include-statement I use. Moreover, no matter which statement I use I can access SFML-library from any point in my project. Does it have to do with the SFML-directory being in the "include"-directory in my project?
UPD 2:
Okay, problem solved and it had nothing to do with #include <> and #include "". I just had to put "..\" before writing the name of the path and it worked beautifully. I marked the answer that suited the best right.
You have to correctly configure include header paths settings in your IDE/Makefile. To put simply, to be able search a particular header file, a compiler must know where to look for it. For example, in g++, we use -I flag to provide various include paths.
For example,
$g++ -I/usr/abc/A/ main.cpp
In main.cpp, a.h is included and aboslute path of this file is /usr/abc/A/a.h.
You can:
Add the directories which have the required header files as part of pre-processor lookup. Different compilers have different way to achieve this.
Add the header file as a relative path. For eg. #include "../folderName/A.h"
Combine 1. and 2. Add a top level directory in the search path and include files as #include "topLevelDirectory/A.h"
I personally do not like 2. because if your file hierarchy changes you will have to modify source code to change the relative paths.

Why don't I need to include library.cpp in the header?

I have a question about libraries. When I write a library I have 2 files: library.h and library.cpp.
The first one contains the prototypes of the functions and the second one contains the definitions. Well, in library.cpp I include #include "library.h", so they are connected in one way, but what happens with the header? Why don't I have to write #include "library.cpp" in the header?
When I use the library in the main file, I write #include "library.h", which includes the prototypes, but how does the compiler know where the definitions are?
Explained briefly:
(1) Your library.cpp file is sent to the preprocessor.
(2) The preprocessor reads the line #include "library.h" and goes and finds the file library.h.
(3) The contents of library.h are literally copied into the library.cpp file.
(4) The library.cpp file is compiled and linked with the main file.
Thus, all of the "prototypes" in the header are copied into the top of the implementation file. .cpp files are compiled and linked. The header files themselves are not compiled -- their contents are copied into the .cpp files.
There is a tool called linker which is responsible for link your generated object files. You should look for compilation process to understand it better.
The preprocessor pulls the header file into the CPP file, so the compiler sees the prototypes and the definitions together.
If you were to pull the CPP file into the header file, you would either send the preprocessor into an infinite loop, or by using
#ifndef __FOOBAR__
#define __FOOBAR__
(code file)
#endif
around the header AND source files you would read the file just once.
All the cpp files are compiled seperately and the code is accumulated in a big pile somewhere. The linker collects all the symbols in your code and assigns them an address within this pile. So although your file doesn't see library.cpp directly, it knows the symbols from library.h and the assigned addresses. It can then zoom directly to the required code in the big pile. Not the most technical answer I know..
It was my understanding that when you type #include "library.h" in your code the compiler is set to also load library.cpp. I was taught in school that there isn't really any way to break this connection unless you were to manually compile and link each file either using compiler commands or a makefile appropriate for the system you're using (Windows, *nix, MacOS, etc.)
You have to type #include "library.h" in the library.cpp file because that is where the function prototypes are stored. You can "cheat" and put the function prototypes in the .cpp file and just type #include "library.cpp" but this is bad practice and is generally discouraged in the programming community.

Accessing functions from external files in class definition

I'm trying to access functions from another file for use inside my class definition:
// math.cpp
int Sum(int a, int b){
return (a + b);
}
// my_class.cpp
#include <math.cpp>
#include <my_class.h>
int ComputeSomething() {
...
return ::Sum(num1, num2);
}
Despite my best efforts, I can't get the compiler to spit out anything outside the likes of ::Sum has not been declared or Sum was not declared in this scope.
I'm trying to wrap my head around code organization in C++, any help appreciated.
It might be worth noting that I'm programming for Arduino.
To be able to access functions from a user-defined library, best divide that library into a .h (or .hpp) and a .cpp file. I understand you have actually done this, but tried various options – among them the inclusion of the .cpp file – for the sake of finding a solution.
Still, to ensure things work as expected, the declarations of functions and classes should go into the .h file, best protected by something like
#ifndef MY_H_FILE
#define MY_H_FILE
/* ..Declarations.. */
#endif
Then to include the .h file (I'll assume it's named my.h), either use
#include "my.h" // path relative to build directory
or
#include <my.h> // path relative to any of the include paths
The latter only works if my.h is found on an include path previously known to the compiler (e.g. what is specified using the -I command line option in GCC). The former works if the path to the .h file given is relative to the directory your are building from.
Finally, do not use a file name that can be confused with a system library (such as "math.h"), especially if you are using the <...> syntax, as the include path will definitely include the system library header files.
Have you followed the instructions given here?
User-created libraries as of version 0017 go in a subdirectory of your
default sketch directory. For example, on OSX, the new directory would
be ~/Documents/Arduino/libraries/. On Windows, it would be My
Documents\Arduino\libraries. To add your own library, create a new
directory in the libraries directory with the name of your library.
The folder should contain a C or C++ file with your code and a header
file with your function and variable declarations. It will then appear
in the Sketch | Import Library menu in the Arduino IDE.

dealing with includes and using headers

I have "Hello World" code that uses function fhi from another hi.cpp file that has it's header.
Correct my if my understanding is wrong according following:
I can do include cpp file like #include "c:\c\hi.cpp" instead of using header without any problems except that fact that it looks more readable in header file.
If I include header like sample in my main program hi.h, must hi.h include hi.cpp, or it is done automatically according the same file name hi. I'm wondering how compiler knows where is function fhi body.
Is it possible to have different names for header and cpp files?
Programm:
#include "stdafx.h"
#include "c:\c\hi.h"
int _tmain(int argc, _TCHAR* argv[])
{
fhi(1);
return 0;
}
hi.h
#include <cstdlib>
#include <iostream>
int var;
int fhi(int f);
hi.cpp
#include <cstdlib>
#include <iostream>
int fhi(int f)
{
return 0;
}
must hi.h include hi.cpp
No. hi.h contains only declarations, that can be other by other .cpp files.
I'm wondering how compiler knows where is function fhi body.
It doesn't. You need to compile all *.cpp files into the object files. In your case, you will have two object files: program.o and hi.o. The linker can now take these two object files, and spit out the executable. References to other functions(in this case the actual definition of fhi(..)) is resolved in this stage.
Also why are you using absolute paths in #includes? It will break when you move the "c" directory around.
What normally happens is that the build system compiles the .cpp files into object files, that then are used to build the main executable. The means to tell this to the build system vary greatly.
One important point is that your hi.cpp must include hi.h. You should also put an include guard in hi.h, to make it safe to be included more than once in a translation unit.
I can do include cpp file like #include "c:\c\hi.cpp" instead of using
header without any problems except that fact that it looks more
readable in header file.
yes, you can do so but it is not recommended, one of the problems is encapsulation; you are not hiding implementation details. readability as you mention is also a concern, a header is easier to read since it clearly shows what methods are public.
If I include header like sample in my main program hi.h, must hi.h
include hi.cpp, or it is done automatically according the same file
name hi. I'm wondering how compiler knows where is function fhi body.
the header needs to be explicitly included in hi.cpp and any .cpp file that use the class defined in the header.
Is it possible to have different names for header and cpp files?
yes but it is not recommended, it makes it more difficult to find things.
as a general rule: think about that other programmers may want to look in your code so you need to structure it so that it is easy to read and understand as well as making it easier for you 2 years down the road to remember where things are.
In Visual Studio all CPP files included in the project will be compiled to produce OBJ files. These OBJ files will be linked together to form the EXE or DLL.
Including files are similar to pasting the contents of the file at that location. The only difference is that this pasting is done by the pre-compiler during compilation.
Finding out where a function body resides is done by the either the compiler if the function is inline or by the linker when the final binary is created.
First, if the header file is in the same directory as the source file including it, you can use just
#include "hi.h"
In other words, you don't have to use a full path. (See e.g. the inclusion of "stdafx.h".)
Second, in your header file you don't need to include other header files, unless you need types from those. In your header file you don't have anything that needed from the header files you include.
Third, you should protect header files header files from being included more than once in the same source file, this can be done with a so called include guard, on in some compiler via a special directive called #pragma once.
Fourth, in your header file you define a global variable var. This variable will then be defined in every source file you include the header file in, which will lead to errors. You need to declare the variable as extern:
extern int var;
Then in one source file you define the variable like you do now.
Fifth, you should never include source files in header file (with some special exceptions that you don't have to think about yet). Instead you add all source files to the project (I assume you are in MS VisualStudio) and it they will all be built and linked together automatically.
Sixth, since you seem to be using VisualC++, then you are probably using something called precompiled headers. This is something the compiler uses to speed up compilation. However, for this to work you have to include "stdafx.h" in all source files. That include actually has to be the first non-comment line in each source file.

How does C++ handle multiple source files?

I'm studying C++ right now, coming from a background in Python, and I'm having some trouble understanding how C++ handles multiple source files. In Python, the import statement first checks the current working directory for the module you're trying to import and then it checks the directories in sys.path. In C++, where would I place a custom made .h file? Where would the compiler even look?
For example, I've got a program, foo.exe compiled from a single source file, foo.cpp, both in the same directory. I decide that I want to organize things a little better, so I create a new .h file, bar.h and dump stuff in there. Would I just need to #include to get to the stuff I put there? What if I want to use bar.h with another program (in a completely different directory)?
There are two include variants:
#include "path-spec"
#include <path-spec>
Quote notation:
This form instructs the preprocessor to look for include files in the same directory of the file that contains the #include statement, and then in the directories of any files that include (#include) that file.
The bracket notation looks for header files in certain defined locations.
With gcc you can get some information about these pathes via:
$ echo | gcc -v -x c++ -E -
Compilers accept
-I or /I
options to add additional pathes.
It (generally) looks in the include path if you use #include <foo>, else it uses relative paths if you use #include "../../foo/bar.h".
You set the include path with -I or /I on most compilers. Consult its manual for details.
Don't define any objects in headers though -- you will have multiple definition errors at link time if you do (and include the header in multiple source files).
It works in a similar way. The #include only is used by the compiler. In execution time the file bar.h doesn't gets used. But in compile time it is.
In compile time, the file could be in two places:
1.- The current directory (as in python)
2.- The directories configured in your include path. Where to configure that directories depends of the compiler you are using. Most of them let you define the include directories in the compile command line. And most IDEs let you configure it in some Options menu.
Hope it helps.
If your header files are in the same dir, you can include them like:
#include "bar.h"
If you want to include this header from another dir:
#include "../foobar/bar.h"
Basically quotations mean to search from current directory and brackets like in #include <abc.h> mean to search in standard header file directories. You can add custom directories to the standard search path by adding a -I /path/to/your/custom/headers in the compile command.
#include with angle brackets looks in the system include directories. Like this:
#include <iostream>
With double quotes it looks in the current directory and other directories given to the compiler to search.
#include "foo.h"
g++ -I../include foo.cpp
the thing you are missing in the python model is the linker.
in python you import code and its interpreted right there and then. in c/c++ you compile each source file into an object file. You then tell the linker to collect a bunch of object files into an executable
Typically the includes in c/c++ source files only contain descriptions of whast in the other C files (the names of functions, etc) not the function contents. This is enough for the compiler to compile a given file. Then the linker will combine your object files with libraries of 'well known' functions and make an executable