So, as far as my cpp knowledge goes, I can call functions which are declared/defined in header files I #include.
Is there any possibility to call functions from the file that includes?
For example: "main.cpp" includes "test.h", So any function from "main.cpp" can make calls to functions from "test.h".
But, in that case, can code from "test.cpp" make calls to functions from "main.cpp" without including it?
No. You cannot call functions declared in another source files from another source files. Also what is the in that? And a good usage separate source from header; Header files include prototypes and declarations while source includes definitions.
eg:
// Shape.h
#ifndef SHAPE_H
#define SHAPE_H
class Shape{
//...
};
#endif
// Shape2D.h
#ifndef Shape2D.h
#define Shape2D.h
class Shape2D{
//...
};
#endif
Now source files:
// Shape.cpp
#include "Shape.h"
// Definitions here:
Shape::Shape(){}
// Shape2D.cpp
#include "Shape2D.h"
// Some definitions here:
Shape2D::Shape2D(){}
Now in main.cpp:
#include "Shape2D.h"
// #include "Shape.h"
int DoSomeStuff();
int main(){
Shape2D a;
Shape b;
return 0;
}
int DoSomeStuff(){
// ....
}
As you can see above I just included Shape2D.h
and can use class Shape
without including its header file Shape.h
That is because Shape2D.h
includes it so it's content is added to it then all the content of two files is present in my main source file.
Main.cpp
includes Shape.h
indirectly.
Try to something like this:
In Shape.cpp
call DoSomeThing
:
#include "main.cpp"
int x = DoSomeThing();
Above there's at least a compile-time errors: At least class Shape
and Shape2D
are already defined.
What I recommend: Don't include source files, Use Inclusions guards
or pragma once
to avoid multiple file inclusion.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.