How to let ld link the function in a header file?

2

I have a self-defined function strlen() in lib.h

inline int strlen(char * String)
{
    register int __res;
    __asm__ __volatile__    (   "cld    \n\t"
                    "repne  \n\t"
                    "scasb  \n\t"
                    "notl   %0  \n\t"
                    "decl   %0  \n\t"
                    :"=c"(__res)
                    :"D"(String),"a"(0),"0"(0xffffffff)
                    :
                );
    return __res;
}

which is invoked in printk.c

#include "lib.h"
....
len=strlen(s);

and when I try to link printk.o,which is complied successfully by gcc

ld -b elf64-x86-64 -z muldefs -o system head.o main.o printk.o -T kernel.lds 

I get

ld: printk.o: in function `vsprintf':
printk.c:(.text+0x7b1): undefined reference to `strlen'

I tried to use -L,but it doesn't work. Any ideas are appreciated.

c
asked on Stack Overflow Nov 2, 2020 by Phyzaitlu • edited Nov 2, 2020 by Phyzaitlu

1 Answer

2

In C, when you declare a function as inline, you must also declare it as extern in one (and only one) compilation unit. So in one (and only one) of your .c files that has an #include "lib.h" add extern int strlen(char *); to get an extern definition of the inline function in that compilation unit to satisfy any link requests that did not get inlined (for whatever reason).

When you declare a function as inline without extern, it defines a version of the function that can be inlined into any call site it that compilation unit, if the compiler chooses to do so, but will not be included as a "standalone" function. There is, however, no guarentee that any given call or use will be inlined (and generally, it will only be inlined if you enable optimization). So if there are any non-inlined references to the function, you need to ensure that there is an extern definition of the function somewhere.

answered on Stack Overflow Nov 3, 2020 by Chris Dodd • edited Nov 12, 2020 by Chris Dodd

User contributions licensed under CC BY-SA 3.0