0

I have problem with pthread_mutex_t. When I try to create static field pthread_mutex_t, then initialize it in static function and finally use it within some class methods I get many errors like:

main.o: In function `LogWriter::initialize(pthread_mutex_t*)':
 main.cpp:(.text._ZN9LogWriter10initializeEP15pthread_mutex_t[LogWriter::initialize(pthread_mutex_t*)]+0x7): undefined reference to `LogWriter::mutex'

Simpplified class code:

class LogWriter{
    static pthread_mutex_t mutex;

    static void initialize(pthread_mutex_t *mut){
    LogWriter::mutex = PTHREAD_MUTEX_INITIALIZER;
    //if(pthread_mutex_init(&(LogWriter::mutex), NULL) != 0){
        //init failed
    //}
    }
    public:
    static LogWriter getInstance(string module_name){
    LogWriter  instance(module_name);
    return instance;
    }

    LogWriter& operator<<(string a);
};

My quesiton is: why ? I know that if I define it as normal (non-static) field I won't have any problems. Also searched google but I couldn't find any materials that are linked with this. Also creating pointer to static pthread_mutex and initializing in in main function ends like this.

lagoru
  • 697
  • 1
  • 12
  • 22
  • 4
    You need to define the static member in one and only one source file. `pthread_mutex_t LogWriter::mutex;`. This is true for all `static` members and has nothing to do with `pthread_mutex_t` in general. – Alok Save Mar 10 '13 at 14:51
  • O I get it - I didn't know about such limit - thanks :) – lagoru Mar 10 '13 at 15:02

1 Answers1

5

In some source file in your code, you need to add:

static LogWriter::pthread_mutex_t mutex;

The compiler won't "place" your variable in any particular source file, you have to do that for it. The class declaration just tells the compiler "I'll have a static variable somewhere" - but since, at least in theory, variables ordering and placement can make a difference [you may for example have different object files product "data" that goes into different sections of memory in some embedded system], the compiler won't be able to just throw it in any place it likes - that could be somewhere you don't want it.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227