Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simple C inline linker error

simple problem:

given the following program:

#include <stdio.h>

inline void addEmUp(int a, int b, int * result)
{
    if (result) {
        *result = a+b;
    }
}

int main(int argc, const char * argv[])
{
    int i;
    addEmUp(1, 2, &i);

    return 0;
}

I get a linker error...

Undefined symbols for architecture x86_64:
  _addEmUp", referenced from:
      _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

seems as though it doesn't bother to compile it.

it shouldn't need to be static, I wouldn't think, based on what I have read in:
Linker error inline function (as this is in a different object, and dealing with 2 definitions rather than zero)

This is a related link, but it is c++ and I don't think it is good practice in std C to put code in the header:
inline function linker error

compiler info:

cc --version
Apple LLVM version 4.2 (clang-425.0.28) (based on LLVM 3.2svn)
Target: x86_64-apple-darwin12.3.0
Thread model: posix

compilation example:

# cc main.c 
Undefined symbols for architecture x86_64:
  "_addEmUp", referenced from:
      _main in main-sq3kr4.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocatio
like image 602
Grady Player Avatar asked May 24 '13 17:05

Grady Player


2 Answers

Paragraph 7 of section 6.7.4 says:

Any function with internal linkage can be an inline function. For a function with external linkage, the following restrictions apply: If a function is declared with an inline function specifier, then it shall also be defined in the same translation unit. If all of the file scope declarations for a function in a translation unit include the inline function specifier without extern, then the definition in that translation unit is an inline definition. An inline definition does not provide an external definition for the function, and does not forbid an external definition in another translation unit. An inline definition provides an alternative to an external definition, which a translator may use to implement any call to the function in the same translation unit. It is unspecified whether a call to the function uses the inline definition or the external definition.

Your file does not contain an external definition of addEmUp, and the compiler chose to use the external definition in the call in main.

Provide an external definition, or declare it as static inline.

like image 198
Daniel Fischer Avatar answered Oct 15 '22 15:10

Daniel Fischer


Try adding the "-O" option to your compiler command. Inlining is turned on only when optimization is enabled.

like image 44
Ziffusion Avatar answered Oct 15 '22 14:10

Ziffusion