0

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!

Łukasz Przeniosło
  • 2,725
  • 5
  • 38
  • 74

2 Answers2

3

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);)

petersohn
  • 11,292
  • 13
  • 61
  • 98
  • Okaay so I undrestand that in c++ static is the same as in c. But now I am really confused on how am I supposed to declare functions and variables in a namespace to access them everywhere. – Łukasz Przeniosło Jun 11 '15 at 08:32
  • You can access a function from a namespace like this: `CProfileIO::setAppDir("something");` – petersohn Jun 11 '15 at 08:35
  • I know but I dont know how to construct the namespace files in a "proper" way. Fow now I have moved functioncs definitions from .cpp file to .h file as I would do in standard c and it works, but it doesnt look good. – Łukasz Przeniosło Jun 11 '15 at 08:37
  • It is perfectly OK how you did it here. – petersohn Jun 11 '15 at 09:09
1

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?

  • I had a class instead of a namespace in the beginning, but then I read that I am supposed to have namespace instead. I tried to follow this solution http://stackoverflow.com/a/112451/1036082 – Łukasz Przeniosło Jun 11 '15 at 08:26