Simple C inline linker error

纵饮孤独 提交于 2019-11-27 06:14:06

问题


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

回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/16740515/simple-c-inline-linker-error

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!