1

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$

oinererhuf
  • 11
  • 2
  • 3
    Link order is significant. Try `gcc -L. -o testlib main.c -lmylib` – Nate Eldredge Nov 16 '20 at 15:44
  • When I change the order of the gcc command, I am able to compile the code. – oinererhuf Nov 16 '20 at 15:49
  • `int get_var()` indicates a function that takes an unknown/indeterminant number of arguments. `int get_var(void)` is a function that takes no arguments. The former should not have been written any time this century. – William Pursell Nov 16 '20 at 16:07

0 Answers0