Reputation:
If using my own files:
abc.cpp abc.h
Lets say abc.h contains:
//abc.h
#ifndef ABC_H
#define ABC_H
void function1 ();
#endif
Lets say abc.cpp contains:
//abc.cpp
void function1();
void function2();
void function1(){
function2();
}
void function2(){
}
If I want to access function2 by means of the code in function 1, Do I absolutely need to do this still:
//abc.h
#ifndef ABC_H
#define ABC_H
void function1 ();
void function2 ();
#endif
Or can I just leave it like this:
//abc.h
#ifndef ABC_H
#define ABC_H
void function1 ();
#endif
Thanks in advance for any help. Andrew B
Upvotes: 1
Views: 229
Reputation: 10740
The rule in C++ is declaration before use. This means that you have to declare that a function exists before it's used.
int add(int, int);
This takes one of 3 forms:
These functions aren't visible outside of the cpp file they're defined in:
// foo.hpp
// Declaration
void foo();
// foo.cpp
// Definition
void do_some_stuff() {
std::cout << "Hello, world!\n";
}
// Definition
void foo() {
do_some_stuff();
}
Because C++ uses textual inclusion for header files, you can have functions defined in the header file, and they can access functions defined in the cpp file as long as the declaration comes first:
// example.hpp
// declaration comes before usage
void printMessage(); //Defined in Cpp file
void printMessage10x() {
for(int i = 0; i < 10; i++) {
printMessage();
}
}
// example.cpp
void printMessage() {
std::cout << "Hello, world!\n";
}
This works because the declaration for printMessage
occurs earlier in the header file, so it's visible to the compiler.
Functions declared in a header file can be inlined without having to resort to Link-time Optimization. In addition, there's more information availible to the compiler when it's considering whether or not to inline the function.
Additionally, templated classes and functions are easiest to use when they're declared within the header file. See this question for more information.
// min.hpp
// Calculates the minimum of two numbers of any type
template<class T>
T min(T a, T b) {
if(a < b)
return a;
else
return b;
}
Upvotes: 1