3

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.

3
  • inline works differently in C and C++. Which one do you mean? Nov 2, 2020 at 14:53
  • Just c.Thanks for reply and I update the label
    – Phyzaitlu
    Nov 2, 2020 at 15:12
  • Did you try to use addr2line to find out which line triggers the message? (I'm not sure but think this tool should be helpful.) -- Did you try to minimize the code into a minimal reproducible example for us to reproduce? Nov 2, 2020 at 17:20

1 Answer 1

3

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.

2
  • Thanks,it works.As far as I learnt, extern is used for variables across files.
    – Phyzaitlu
    Nov 3, 2020 at 15:59
  • extern is used to make a symbol globally visible across a program, rather than local to one compilation unit.
    – Chris Dodd
    Nov 3, 2020 at 23:08

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.