1

test.c:

#include <stdio.h>
int main(){
    return printf("helloworld %d",a);
}

lib.c:

int a=0;

test.c is using the variable a from lib.c. I turned it into the shared library lib.so.

gcc testbench.c -o test -l lib.so

throws an error :

‘a’ undeclared (first use in this function)

This is unexpected, since it was declared in lib.c.

4
  • Note the return value of printf, is not compatible with the return value of main. (I did not say type, the type is compatible). Commented Feb 17, 2020 at 17:40
  • @ctrl-alt-delor What problem do you see here? both functions have an int as return type and both have the same permitted range.
    – schily
    Commented Feb 17, 2020 at 17:43
  • 1
    The type is compatible, the meaning is not. Commented Feb 17, 2020 at 17:44
  • You need to have extern int a; in testbench.c. Note that there are platforms like macOS that use a stone age linker that does not support to link against variables inside shared libraries but all platforms that are based on SunOS dynamic linker code will work.
    – schily
    Commented Feb 17, 2020 at 17:45

2 Answers 2

1

You need to communicate the compiler that a exists externally to the source file. To do that, declare it as extern:

#include <stdio.h>

extern int a;

int main(void)
{
    printf("helloworld %d", a);
    return 0;
}
0

This has nothing to do with dynamic, the same problem will happen with static linking.

The problem is that you have not declared it. You have however defined it. You need to declare it with extern int a;, before it is used.

You should do this in a file named lib.h (same name as the compilation unit, and include it from lib.c (to verify it), and from main.c to use it.

main.c

#include "lib.h"
#include <stdio.h>
int main(){
    printf("helloworld %d",a);
    return 0;
}

lib.h

extern int a;

lib.c

#include "lib.h"
/*other includes that we need, after including own .h*/
/*so we can catch missing dependencies*/
int a=0;

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .