如何将函数从标题文件中包括到多个CPP文件

问题描述 投票:0回答:2

我想以这种方式定义自动返回类型的函数,如果我包含标头,我可以从多个.cpp文件调用它。 我有4个文件

head.hpp
-函数为

#ifndef HEAD_HPP
#define HEAD_HPP 

auto f();

#endif

head.cpp
-声明函数的地方

#include "head.hpp"

auto f(){
    return [](){
        return 10;
    };
}

test1.cpp
-在哪里使用

#include "head.hpp"
int foo(){
    auto func = f();
    return f();
}

main.cpp
-在哪里也使用了

#include "head.hpp" int foo(); int main(){ auto fu = f(); return fu() + 5 + foo(); }
所有文件complate
我仍然有错误:

Error:在扣除“自动”之前使用“ auto f()”

auto fu = f();

不幸的是,C ++不起作用。

当您在C ++中调用函数时:

auto fu=f();
c++ lambda header auto include-guards
2个回答
7
投票
编译器必须知道该函数实际返回的离散类型。

auto

不是真正的类型。这只是稍后可以弄清楚一种类型的占位符。

但是这个“以后”永远不会到来。如果编译器所看到的所有内容都是

auto
返回类型,则编译器无法确定函数的实际返回类型,因此,该程序是不形成的,您会遇到编译错误。

这是C ++的基本方面,没有解决方法。

填写标题。将

f

的定义放在

模块中。
// head.cpp export module head; export auto f() { // whatever }

然后在另一个tu中导入该模块。

// main.cpp import head; int main() { ... f() ... // whatever }

0
投票
现在,

f

的类型在
main.cpp中很神奇。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.