gpt4 book ai didi

c++ - 编译包含在 header 中声明的函数的源文件

转载 作者:太空宇宙 更新时间:2023-11-04 15:24:33 25 4
gpt4 key购买 nike

假设有一个源文件un2.cpp

----un2.cpp----

class employee;
void employee::setname(string s)
{
.....(some code)
}

employee 类在 un2.h 中定义,其中声明了 setname()。现在,当我尝试通过“cc -c un2.cpp -o un2.o”编译 un2.cpp 时,我收到一条错误消息

 un2.cpp:3:16: error: invalid use of incomplete type ‘struct employee’
un2.cpp:1:7: error: forward declaration of ‘struct employee’

为什么编译器不直接将 employee 作为外部符号(就像它会采用先前声明但 undefined symbol 一样)并编译 un2.cpp 文件。

编译一个普通的undefined symbol和一个undefined class有什么区别吗?还有谁能告诉我(如果可能的话)如何转发声明一个类并在其中定义符号吗?

最佳答案

external 用于链接器,在您编译代码时不会帮助您,因为编译器仅通过编写前向声明不知道您的类声明。

相反,您需要在 un2.cpp 文件中包含带有声明的 header 才能编译。

关于c++ - 编译包含在 header 中声明的函数的源文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11969778/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com