1

I am trying to link two libraries libA.a and libB.a along with a main.c file. libB has dependencies on libA, and main has dependencies on both.

I am able to compile the libraries independently, but when I try to link them together to create the final executable, I get the error that references to functions of A by B are not defined.

Is there any way to tell the linker to search for these functions in libA?

  1. I am going to run this code on FreeRTOS on Cortex-M3 MCU so static linking is my only option.
  2. I really want to be able to do this without changing the compile process for libB.

There is a similar question at this link but as I said, dynamic linking is not an option.

As requested by Ofek a toy code (ignore functionality and syntax errors, if any)-

libA

int libA_fun1()
{ return stuff; }

int libA_fun2()
{ return something_else; }

libB

#include <libA.h>

int libB_fun1()
{
    //do stuff
    int x = libA_fun1();
    return something;
}

main.c

#include <libA.h>
#include <libB.h>

int main()
{
    printf("%d", libA_fun2() * libB_fun1()); 
    return 0;
}

I build libA.a and libB.a. Finally

gcc main.c -lA -lB -LPathA -LPathB

gives the error: undefined reference to libA_fun1 in libB_filexx.c, line xx

However, the function is properly defined in libA.h

TSG
  • 877
  • 1
  • 6
  • 23
  • This scenario is fully supported. Can you post the exact error message? Even better - a toy code demonstrating the linkage error? – Ofek Shilon May 29 '15 at 18:58
  • @OfekShilon - I have updated with an example – TSG May 29 '15 at 22:44
  • What you're doing, generally-speaking, should be perfectly fine (provided that there are no circular dependencies), so I'd look to build settings otherwise. This is a goofy guess, but I've been bitten before ages ago due to linker order. Try reversing the order in which you link `main` against `A` and `B`. Ex: `gcc main.c -lB -lA -LPathB -LPathA` –  May 29 '15 at 22:54
  • Hey guess what! That worked!! How?!! – TSG May 29 '15 at 23:22

1 Answers1

2

Thanks to @Ike for suggesting a fix which worked.

In short:

If any [static] library B depends on symbols defined in library A, then library B should appear first in the list supplied to the linker. A more detailed explaination can be found here.

The order in which librries appear to the linker is important too, and that is where my linking command was failing.

Community
  • 1
  • 1
TSG
  • 877
  • 1
  • 6
  • 23