Linking error for inline functions

本秂侑毒 提交于 2019-12-03 14:55:11

问题


I am trying to compile the sample code "SonofGrab" using XCode 4.5.1 on OS X 10.8.

One function is defined like this in controller.m

inline uint32_t ChangeBits(uint32_t currentBits, uint32_t flagsToChange, BOOL setFlags);

This leads to this error message:

Undefined symbols for architecture x86_64:
"_ChangeBits", referenced from:
-[Controller awakeFromNib] in Controller.o
[...]
ld: symbol(s) not found for architecture x86_64

Removing the inlining of the function ChangeBits solves the problem, but why does the linker not find Changebits with the original definition ?


回答1:


That to me, looks like a bug. This simple case exhibits the same error:

inline void foo() {}
int main() {
    foo();
}

Yields:

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

That has got to be wrong!? Unless I'm totally missing something about inline.

Edit: Oh no, wait, check out this - http://clang.llvm.org/compatibility.html#inline

Basically it appears I didn't understand inline fully, either. And nor did the person writing that sample code at Apple!

The inline on the ChangeBits function means that that definition is to be used only for inlining. Not that the function should always be inlined. There must be another, non-inline definition available elsewhere in the application otherwise it's illegal. Hence the link error as no non-inline ChangeBits is provided.

The real solution is to declare ChangeBits as static inline since that tells the compiler that the definition is local to that translation unit only and there does not therefore need to be a non-inline definition.

More information on the LLVM page I linked to, though. Hope that helps!



来源:https://stackoverflow.com/questions/12844729/linking-error-for-inline-functions

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