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 ?
For further actions, you may consider blocking this person and/or reporting abuse
Top comments (3)
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.
Now you can use this context in your app.
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.
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
}
}
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