问题
Since LTO can resolve inline
symbols from other object files, I tried to separate declaration and definition for inline
functions. Here is the 3 files, dep.hpp
, dep.cpp
and main.cpp
, where main.cpp
and dep.cpp
are linked together and dep.hpp
is #include
d in both:
// dep.hpp, declaration
#ifndef _DEP_HPP_
#define _DEP_HPP_
inline void sayHello();
#endif
// dep.cpp, definition
#include "dep.hpp"
#include <iostream>
inline void sayHello() {
std::cout << "Hello World!" << std::endl;
}
// main.cpp, caller
#include "dep.hpp"
int main(int argc, char** argv) {
sayHello();
}
And here's the error that G++ prints:
In file included from main.cpp:1:
dep.hpp: At global scope:
dep.hpp:4:13: warning: inline function 'void sayHello()' used but never defined
inline void sayHello();
^~~~~~~~
C:\Users\vtonc\AppData\Local\Temp\ccojskQy.ltrans0.ltrans.o:<artificial>:(.text+0x15): undefined reference to `sayHello()'
collect2.exe: error: ld returned 1 exit status
The command line:
@echo off
g++ main.cpp dep.cpp -o example.exe -flto -Wall -Wextra
pause
Why is the linker complaining about undefined sayHello()
when -flto
is enabled and sayHello()
itself is inline
? Shouldn't LTO handle such cases?
I'm using mingw-w64 8.1.0 x86_64-posix-seh
.
回答1:
The whole point of inline
is that you must provide the function's definition in the same translation unit(s) in which you call the function.
Turning on a compiler optimisation doesn't change that; it's a rule of the language.
Move the definition to the header.
来源:https://stackoverflow.com/questions/57220421/g-and-lto-how-to-separate-declaration-and-definition