c++staticstatic-functions

How to call static library function in a C++ class?


I have class whose header file is defined as:

namespace mip {
    class CustomStatic {
        public:
            static const char* GetVersion();
    };
}

And class file is defined as:

#include "CustomStatic.h"

namespace mip {
    static const char* GetVersion() {
        return "hello";
    }
}

I am accessing this static function from my main class

#include "CustomStatic.h"

#include <iostream>

using std::cout;
using mip::CustomStatic;

int main() {
    const char *msg = mip::CustomStatic::GetVersion();
    cout << "Version " << msg << "\n";
}

When I try to compile it using-

g++ -std=c++11 -I CustomStatic.h  MainApp.cpp CustomStatic.cpp

I am getting error as:

Undefined symbols for architecture x86_64:
"mip::CustomStatic::GetVersion()", referenced from: _main in MainApp-feb286.o ld: symbol(s) not found for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)


Solution

  • your static function is not properly implemented in the cpp file...

    you need to do something like

    //.h
    namespace mip
    {
        class CustomStatic
        {
             public:
                static const char* GetVersion();
        };
    }
    
    
    //.cpp -> note that no static keyword is required...
    namespace mip
    {
        const char* CustomStatic::GetVersion()
        {
            return "hello";
        }
    }
    
    //use
    int main(int argc, char *argv[])
    {
        const char* msg{mip::CustomStatic::GetVersion()};
        cout << "Version " << msg << "\n";
    }