G ++和LTO:如何将声明和定义分开? [英] G++ and LTO: how to separate declaration and definition?

查看:256
本文介绍了G ++和LTO:如何将声明和定义分开?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于LTO可以解析其他目标文件中的inline符号,因此我尝试将inline函数的声明和定义分开.这是3个文件,分别是dep.hppdep.cppmain.cpp,其中main.cppdep.cpp链接在一起,并且dep.hpp在这两个文件中均是#include d:

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 #included 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();
}

这是G ++打印的错误:

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

命令行:

@echo off
g++ main.cpp dep.cpp -o example.exe -flto -Wall -Wextra
pause

当启用-flto并且sayHello()本身是inline时,为什么链接程序会抱怨未定义的sayHello()? LTO不应该处理这种情况吗?

Why is the linker complaining about undefined sayHello() when -flto is enabled and sayHello() itself is inline? Shouldn't LTO handle such cases?

我正在使用mingw-w64 8.1.0 x86_64-posix-seh.

I'm using mingw-w64 8.1.0 x86_64-posix-seh.

推荐答案

inline的全部要点是,必须在调用该函数的同一翻译单元中提供该函数的定义.

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.

将定义移至标题.

这篇关于G ++和LTO:如何将声明和定义分开?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆