I'm having trouble accessing variables and functions defined in a library. When I tried to create a simple library code, I was still having trouble calling the library functions.
The library .c file is shown below
tony@glroadway:~/testlib$ cat MyLib.c
int abc = 123;
void set_var(int a)
{
abc = a;
}
int get_var()
{
return abc;
}
tony@glroadway:~/testlib$
The main function code is shown below.
tony@glroadway:~/testlib$ cat main.c
#include "stdio.h"
int get_var();
void set_var(int);
int main(int argc, char** argv)
{
set_var(44);
int b = get_var();
printf("%d\n", b);
return 0;
}
tony@glroadway:~/testlib$
The code compilation:
tony@glroadway:~/testlib$ ls -l
total 8
-rw-rw-r-- 1 tony tony 155 Nov 13 22:40 main.c
-rw-rw-r-- 1 tony tony 82 Nov 13 22:15 MyLib.c
tony@glroadway:~/testlib$ gcc -fPIC -c MyLib.c
tony@glroadway:~/testlib$ gcc -shared -o libmylib.so MyLib.o
tony@glroadway:~/testlib$ ls -l
total 28
-rwxrwxr-x 1 tony tony 15704 Nov 16 15:36 libmylib.so
-rw-rw-r-- 1 tony tony 155 Nov 13 22:40 main.c
-rw-rw-r-- 1 tony tony 82 Nov 13 22:15 MyLib.c
-rw-rw-r-- 1 tony tony 1688 Nov 16 15:36 MyLib.o
tony@glroadway:~/testlib$ gcc -L./ -lmylib -o testlib main.c
/usr/bin/ld: /tmp/ccE18z8U.o: in function `main':
main.c:(.text+0x19): undefined reference to `set_var'
/usr/bin/ld: main.c:(.text+0x23): undefined reference to `get_var'
collect2: error: ld returned 1 exit status
tony@glroadway:~/testlib$ gcc --version
gcc (Ubuntu 9.3.0-17ubuntu1~20.04) 9.3.0
Copyright (C) 2019 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Please let me know if I should provide more details. tony@glroadway:~/testlib$