Reputation: 1578
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.
Upvotes: 0
Views: 229
Reputation: 24606
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
.
Upvotes: 2