0

I am having trouble in linking with a static library I created. Here is my directory structure:

test
├── b.c
├── b.o
├── i.h
├── libb.a
└── t
    └── a.c

Here is the content of each file:

i.h:

#include <stdio.h>
void f (int);
#define LENGTH 4

b.c:

#include "i.h"

void f (int i)
{
    printf ("from b.c: %d\n", i);
}

a.c:

#include "../i.h"

int main (void)
{
    f (23);
    printf ("%d\n", LENGTH);
}

To build b.o, I issued: gcc -c i.h b.c. To build libb.a, I issued: ar rcs libb.a b.o.

The command gcc ../b.o a.c (when issued from inside test/t, produces a.out which runs as expected. The problem is when I am trying to link with libb.a using: gcc -L.. -lb a.c from inside test/t. The linker is complaining:

$ gcc -L.. -lb a.c
/usr/bin/ld: /tmp/ccbT50MJ.o: in function `main':
a.c:(.text+0xa): undefined reference to `f'
collect2: error: ld returned 1 exit status

Please let me know what I am missing here.

babon
  • 3,615
  • 2
  • 20
  • 20
  • 1
    Don't pass `.h` files as arguments to `gcc`. There's nothing it can do with them. The individual C files will include them if they need them. And put your library options after the C files that depend on them, otherwise it will skip them. – Tom Karzes Apr 18 '20 at 15:44
  • [Your linkage consumes libraries before the object files that refer to them](https://stackoverflow.com/a/43305704/1362568) – Mike Kinghan Apr 18 '20 at 16:32

1 Answers1

2

You need to put the library at the end (after the source file):

gcc -L.. a.c -lb

The linker searches the library only once when it's seen on the command line. If there were no undefined symbols at that point, it's not looked at again.

From ld(1) documentation:

The linker will search an archive only once, at the location where it is specified on the command line. If the archive defines a symbol which was undefined in some object which appeared before the archive on the command line, the linker will include the appropriate file(s) from the archive. However, an undefined symbol in an object appearing later on the command line will not cause the linker to search the archive again.

P.P
  • 117,907
  • 20
  • 175
  • 238