Subject: RE: Accessing global variables causes segfault
From: "Steve Baldwin" <[email-masked]>
To: "'David Means'" <[email-masked]>
Cc: <[email-masked]>
Date: Sun, 23 Feb 2003 10:48:29 +1100

Thanks for your reply, and I know I stuffed up my example, but there's
still some weird (in my mind) things going on here.  Have a look
at this ...

## Here's where it goes splat ..
##
[cdev]$ cat a.c
#include <stdio.h>
#include <stdlib.h>
extern void fx (void) ;
extern void fx2 (void) ;
extern int *myglobal ;

int
main (int argc, char **argv) {
        fx () ;
        *myglobal = 99 ;
        fx () ;
        fx2 () ;
}

[cdev]$ cat b.c
#include <stdio.h>

int global = 10 ;
int *myglobal = &global ;
void fx2 (void) ;

void
fx (void)
{
        fprintf(stderr, "before fx2 : myglobal = %d\n", *myglobal) ;
        fx2() ;
        fprintf(stderr, "after fx2 : myglobal = %d\n", *myglobal) ;
}

void
fx2 (void)
{
        ++global ;
}

[cdev]$ gcc b.c -o libb.dll -shared
[cdev]$ gcc a.c -o a -L. -lb
[cdev]$ ./a
before fx2 : myglobal = 10
after fx2 : myglobal = 11
Segmentation fault (core dumped)

##
## Now, I simply comment out a call to fx2() in a.c.  The program
## runs OK, but the setting of myglobal in a.c has no effect.
##
[cdev]$ cat a.c
#include <stdio.h>
#include <stdlib.h>
extern void fx (void) ;
extern void fx2 (void) ;
extern int *myglobal ;

int
main (int argc, char **argv) {
        fx () ;
        *myglobal = 99 ;
        fx () ;
//      fx2 () ;
}
[cdev]$ gcc a.c -o a -L. -lb
[cdev]$ ./a
before fx2 : myglobal = 10
after fx2 : myglobal = 11
before fx2 : myglobal = 11
after fx2 : myglobal = 12

##
## Now, I change nothing in the code, but statically
## link b.o with a instead of dynamically calling libb.dll.
## Not only does it work, but it works as I would expect.
##
[cdev]$ gcc b.c -c
[cdev]$ gcc a.c -o a b.o
[cdev]$ ./a
before fx2 : myglobal = 10
after fx2 : myglobal = 11
before fx2 : myglobal = 99
after fx2 : myglobal = 100

##
## Now I build libb.dll as a shared library with all
## the 'extra' stuff mentioned on the cygwin site.
## It also works as expected.
##
[cdev]$ gcc b.c -o libb.dll -shared \
> -Wl,--out-implib=libb.dll.a \
> -Wl,--export-all-symbols \
> -Wl,--enable-auto-import \
> -Wl,--whole-archive \
> -Wl,--no-whole-archive
Creating library file: libb.dll.a
[cdev]$ echo EXPORTS > libb.def
[cdev]$ nm libb.dll | grep ' T _' | sed 's/.* T _//' >> libb.def
[cdev]$ dlltool --def libb.def --dllname libb.dll --output-lib libb.a
[cdev]$ gcc a.c -o a -L. -lb
Info: resolving _myglobal by linking to __imp__myglobal (auto-import)
[cdev]$ ./a
before fx2 : myglobal = 10
after fx2 : myglobal = 11
before fx2 : myglobal = 99
after fx2 : myglobal = 100

--
Unsubscribe info:      http://cygwin.com/ml/#unsubscribe-simple
Bug reporting:         http://cygwin.com/bugs.html
Documentation:         http://cygwin.com/docs.html
FAQ:                   http://cygwin.com/faq/