Reputation: 530
I'm currently learning java at my university and I'm trying to keep up with C++ while we cover new stuff. In java I have static member fields and methods that are independent of objects created. This is what I'm aiming to do in c++.
I have a static function in the Collision.h file.
The program will compile only when I define the static function in the header file.
//.h file
static void debug() //compiles and function is usable
{
std::cout << "DEBUG from the collision class called in main" << std::endl;
}
//.cpp file
// <nothing>
when I define the function in the .cpp file the program will not compile.
//.h file
static void debug(); //does not compile
//.cpp file
void debug() //I've tried with and without static keyword here.
{
std::cout << "DEBUG from the collision class called in main" << std::endl;
}
I'm at a loss as to why this latter situation doesn't work. Are .cpp files only used when an object is created?
Thanks for any help. :)
Upvotes: 2
Views: 493
Reputation: 7324
A free function is already independent from objects. In C++ static
has a few different meanings. For free functions, static
means that the function has internal linkage, meaning it is only visible in the current translation unit (cpp file + headers).
Since your function is declared in a header you don't want the static
keyword, otherwise every file that includes it will need to implement it (they essentially get there own version of the function). You also shouldn't define it in the header - leave it as void debug();
. Define it in a cpp file instead.
Upvotes: 3