Pergunta

There is class:

k.h

class k
{
    static int ii;
    static void foo();
};

k.cpp

#include "k.h"

void k::foo()
{
    ii++;
}

During compile I get the following error message:

error LNK2001: unresolved external symbol "private: static int k::ii" (?ii@k@@0HA)

It's OK. But when I add inline keyword to method, error is disappeared:

class k
{
    static int ii;
    inline static void foo();
};

This is not real-world example, but I don't know what exactly happens in this code, may be someone explain it to me?

Foi útil?

Solução

This code:

#include <iostream>
using namespace std;

struct k
{
    static int ii;
    static void foo();
};

void k::foo() {
    ii=0;
}

int main() {
    // your code goes here
    return 0;
}

gives a linking error, because the function k::foo is output by the compiler, and it references k::ii.

This code:

#include <iostream>
using namespace std;

struct k
{
    static int ii;
    inline static void foo();
};

inline void k::foo() {
    ii=0;
}

int main() {
    // your code goes here
    return 0;
}

does not give a linking error, because the function k::foo is declared inline and is not called from anywhere, so the compiler never actually produces any code for it.

If you add a call to k::foo() inside main, or anywhere else, then you will get a linking error.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top