Trouble with using namespace and static methods

1k Views Asked by At

I am trying to write some namespaces statics methods and variables in order to have a set of functions i can use from anywhere in the code. This is what I have: Header:

namespace CProfileIO
{
    static void setAppDir(std::string appDir);
    static int reloadProfiles();

    static std::string directory;
    static std::list<std::string> profilesList;
}

Source:

namespace CProfileIO
{

void setAppDir(std::string appDir)
{
    directory = appDir;
}

int reloadProfiles()
{
    // ...
}

} // namespace CProfileIO

Then somewhere in the code I have:

#include "CProfileIO.h"

int main(int argc, char * argv[])
{
    string appDir = string(dirname(*argv));
    CProfileIO::setAppDir(appDir);
    .
    .
    .
}

When I try to compile, i get error at the line I am using the function:

... undefined reference to `CProfileIO::setAppDir(std::string)'

I cant figure out what is wrong. I would aprichiate all help!

2

There are 2 best solutions below

4
On BEST ANSWER

You should not use static functions here, as they are visible only in the current translation unit. Thus, you declare a static function which you define (statically) in the cpp, then it won't be visible from other translation units.

You should simply not use the static keyword here, but declare variables (but not functions) as extern.

Also, I recommend to pass the string argument as const reference (void setAppDir(const std::string& appDir);)

1
On

That is because static methods are only visible in the current module, (source file). They are not linked. Hence you other sourcefile doesn't find the function. That is supposed to happen if you use static. I don't know why you would declared naked functions as static, maybe you meant to put them into a class?