Answer the question
In order to leave comments, you need to log in
Why does the compiler error 'appear?
Good afternoon. Compilation is fine, but when linking, an error occurs
/tmp/cc0qoW0L.o: In function `main':
/tmp/cc4Zebx3.o: In function `Script::Script(std::basic_string, std::allocator >)':
A2.cpp:(.text._ZN16SkriptC2ESs [_ZN16ScriptC5ESs]+0x36): undefined reference to `Script::counter'
class Skript {
public:
static int counter;
Skript (string v) : text(v) {
counter++;
}
~Skript() {
counter--; }
class RSA : public Skript{
public:
RSA() : Skript("RSA"){ };
~RSA() { };
int main()
{
Skript *v1 = new RSA(); // Error
// int c1 = Skript::counter;
//delete v1;
Answer the question
In order to leave comments, you need to log in
It was not the compiler that made the mistake, but the linker. This question comes from C times and comes from compilation technology: several compilation units are compiled independently and then put together by a linker (linker).
A static class member is a global variable, and if you declare it in each compilation unit, then which one should the linker take? So we came to the conclusion: static int counter;
in the header - this is the same extern
. In other words, we do not declare a variable, but say: don't worry, compiler, it will be in some compilation unit.
And this issue is solved in the same way as for any extern
'a: in one compilation unit (CPP) we declare.
You can also statically initialize this counter:
Oh yes. And where does this technology with compilation units come from? From assembler. If we have a program for almost the entire memory of 16 kilobytes, then the assembler text is much, much larger than the PC memory. So you have to assemble in parts, and then assemble pieces of semi-finished machine code into a complete program. Finally, in order for the language to work, KiR had to write only the C compiler, and the linker was available.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question