DEV Community

vg283
vg283

Posted on

Accessing from outside the global variables declared inside a shared library.

I have a simple c file (mylib.so)compiled as a .so on Mac. This file has two global variables, one is an integer and the other is a pointer pointing to heap. From outside the .so, i.e..from another file (myapp.c) I see that I can access the global integer variable defined inside the .so but when I try to access the pointer, its value is NULL. I have declared both as externs in myapp.c. Was wondering why the global pointer is NULL ?

Top comments (3)

Collapse
 
loki profile image
Loki Le DEV

Who is responsible to initializing your pointer?
You should have something like an init method in mylib.c to initialize it.

Could you share some code?
It's a bad design anyway, why do you need a global variable in your library?
A better design would be to have a "context structure" containing the data and make the methods of your library work on this structure.

// myLib.h

struct my_lib_context
{
   int* p; // some pointer
};

void my_lib_init(my_lib_context* ctx);
void my_lib_deinit(my_lib_context* ctx);

void my_lib_do_something(my_lib_context* ctx);
// etc
// myLib.c

#include <stdlib.h> 

#include "myLib.h"

void my_lib_init(my_lib_context* ctx)
{
   ctx->p = malloc(sizeof(int)); // init your data here
}

void my_lib_do_something(my_lib_context* ctx)
{
  // Do something on ctx here
}

void my_lib_init(my_lib_context* ctx)
{
   free(ctx->p);
}

Now you can use this context in your app.

// myApp.c

#include "myLib.h"

int main()
{

struct my_lib_context ctx;

my_lib_init(ctx)

// work here.

return 0;
}

Note: it lacks error handling in my example.

I'm not sure it answers your question here but in a general sense you shouldn't rely on global variables. You could make one static context struct for your library in myLib.cc also.

Collapse
 
vg283 profile image
vg283

Thanks a lot for your reply. This is definitely much better than using global variables directly. Since it didnt work, I too had something similar to what you have mentioned. I had getter functions to access the global pointer. I still want to know why exactly the global pointer was NULL. Since the lib and the app both are part of same memory space. Here is a snippet which had the problem.

mylib.c

struct node *pHead;

node *add_new_head(int val)
{
pHead = malloc();
...
...
return pHead;
}

myapp.c

extern node *pHead;

int main()
{
//add, move , delete nodes
node *itr = pHead
while(itr) {
//do something
}
}

Collapse
 
loki profile image
Loki Le DEV

global variables are initialized to 0 by default because they are stored in a different section of memory than automatic variables.

stackoverflow.com/a/14052894/5547634