Behavior of static variable in Template in cygwin dynamic library (dll)

andy wang ypwangreg@gmail.com
Sun Apr 15 14:46:00 GMT 2007


Hi, All,

Recently I met the problem that I have seen the similar problem
reported before in this forum
" cygwin, g++, templates, and DLLs"
http://cygwin.com/ml/cygwin/2006-04/msg00480.html
(1) you have a DLL whose source code includes a template class.
(2) that template class has a static member variable
(3) the DLL and the DLL's client both use a specific instantiation of
that template.
But the DLL has one copy of the static member var, and the app has a
different copy.


I have tested the same case in FC4 with g++ version is 4.0.2 and it's fine.
So my question is the problem is related to GCC (which the current
version I am using in cygwin is 3.4.4)  or it is the limitation of
cygwin?

To solve this problem, the workaround method is when you compile the
DLL's client problem you just comment out the "static member variable"
initialization then the DLL's client will work fine.

================= Test case ============
==> pool.h
#include <stdio.h>

class dummy2 {

};

template<class T>
class pool {
public:
    void static init();
    void static alloc();
private:
    static dummy2* buf;
};

template<class T>
dummy2* pool<T>::buf = 0;

class dummy{

};

template<class T>
void pool<T>::init() {
    if(buf == NULL) {
        buf = new dummy2[256];
        printf("buf = %x, addr=%x, type=%d\n",buf, &buf, sizeof(T));
    }
}

template<class T>
void pool<T>::alloc() {
    printf("buf = %x, addr=%x, type=%d\n",buf, &buf, sizeof(T));
}

==> pooluser.h
class pooluser {
    public:
    void static init(void);

};

==> pooluser.cpp
#include "pool.h"
#include "pooluser.h"

void pooluser::init(void)
{
    pool<dummy>::init();
}

==> test.cpp
#include "pool.h"
#include "pooluser.h"

int main(int, char**)
{
    pooluser::init();
    pool<dummy>::alloc();
    return 0;
}

==> Makefile.test
all:
    g++ -shared -o libpooluser.dll pooluser.cpp
    g++ -o test test.cpp -L. -lpooluser
linux:
    g++ -shared -o libpooluser.so pooluser.cpp
     g++ -o test test.cpp -L. -lpooluser
    export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:.


 ======================= test result ================
cygwin on Win, gcc 3.4.4:
$ ./test.exe
buf = 100101f0, addr=10005030, type=1
buf = 0, addr=402000, type=1

linux on FC4, gcc 4.0.2

[root@localhost ypwang]# ./test
buf = 8c7a008, addr=8049820, type=1
buf = 8c7a008, addr=8049820, type=1

--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Problem reports:       http://cygwin.com/problems.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/



More information about the Cygwin mailing list