I've recently run into a problem with compiling a piece of code after upgrading debian testing, getting the gcc 6.2.1 compiler. I've boiled it down to this simple example:
inline int func(void) {
return 0;
}
int main (int argc, char **argv) {
func();
}
The code does not compile with the following:
gcc -o exec code.c # gcc 6.2.1
It fails with:
undefined reference to 'func'
I have also tried and failed with gcc 4.8, 4.9 and 5 on the same host. It does compile if I add:
gcc -o exec code.c -O2 # gcc 6.2.1
I'm really curious as to why it works with the -O2 flag but not without, I'd expect this to work?
Adding the "-O" option to your compiler command. Inlining is turned on only when optimization is enabled.
C99 inline functions
By default, Clang builds C code in GNU C11 mode, so it uses standard C99 semantics for the inline keyword. These semantics are different from those in GNU C89 mode, which is the default mode in versions of GCC prior to 5.0. For example, consider the following code:
inline int add(int i, int j) { return i + j; }
int main() {
int i = add(4, 5);
return i;
}
In C99, inline means that a function's definition is provided only for inlining, and that there is another definition (without inline) somewhere else in the program. That means that this program is incomplete, because if add isn't inlined (for example, when compiling without optimization), then main will have an unresolved reference to that other definition. Therefore we'll get a (correct) link-time error like this:
Undefined symbols:
"_add", referenced from:
_main in cc-y1jXIr.o
By contrast, GNU C89 mode (used by default in older versions of GCC) is the C89 standard plus a lot of extensions. C89 doesn't have an inline keyword, but GCC recognizes it as an extension and just treats it as a hint to the optimizer.
There are several ways to fix this problem:
All of this only applies to C code; the meaning of inline in C++ is very different from its meaning in either GNU89 or C99.