Is it possible to call function defined in a.cpp to use in b.cpp without declaring the function in a.cpp in any header file.
1 Answer
Yes, although it's not recommendable.
What the inclusion of headers actually does is effectively putting the content of the header into the source code at the exact location where the preprocessor finds the #include directive. So, instead of using a include directive, the code can manually be written at that location, the program will be the same:
With headers:
//a.h
void foo();
//a.cpp
#include "a.h"
void foo() {
//do something
}
//b.cpp
#include "a.h"
void bar() {
foo();
}
After preprocessing it's the same as:
//a.cpp
void foo();
void foo() {
//do something
}
//b.cpp
void foo();
void bar() {
foo();
}
So you can leave out the header and declare the function manually everywhere you need to call it. The header however ensures that the declarations are the same all over the project. E.g. if you change foo to take a parameter:
//a.h
void foo(int);
Now in b.cpp the compiler will tell you that the call foo() does not match the declaration. If you leave out the headers and manually declare it instead and if you forget to change the declaration in b.cpp, the compiler will assume there are two versions of foo, because you told him so:
//a.cpp
void foo(int); //version 1
void foo(int i) {
//do something
}
//b.cpp
void foo(); //oops. forgot to change that. compiler assumes a second version
void bar() {
foo(); //ok, try to call version 2...
}
This will compile, however the linker will tell you something about an undefined reference for void foo(), called in b.obj.
4 Comments
a.hpp, i.e. the function with its body. I am not meaning to be picky, but if you use the proper terminology people will understand better what you are talking about. And yes, you have to declare a function before you can use it. However, if you tell us why you think you have to do it, i.e. tell us what you are trying to achieve (instead of how), we probably can show you how to make the better use of headers.a.cpp, of course.
b.cpp, before use. The obvious question would be "what problem are you trying to solve?"