我的C++类在链接到另一个.cpp文件中的函数时遇到问题

My C++ class is having trouble linking to a function in another .cpp file

本文关键字:函数 问题 遇到 文件 cpp C++ 链接 另一个 我的      更新时间:2023-10-16

我昨天问了同样的问题,但答案不适用。

https://stackoverflow.com/questions/6194578/breaking-up-class-functions-into-multiple-cpp-files

如果我进入类标题,右键单击函数并单击";转到定义";它会让我直接进入另一个.CPP文件中的函数。它看到了它,可以链接到它,但我仍然收到错误,表明我看不到它

有人有什么建议吗?我什么都试。

这又是一个错误。

zdll.lib(d000050.o):警告LNK4078:发现多个具有不同属性的'.text'节(E0300020)

WLD.obj:错误LNK2019:函数"public: bool __thiscall WLD::init(unsigned char *)" (?init@WLD@@QAE_NPAE@Z) 中引用的未解析外部符号"public: void __thiscall WLD::fragment_03(unsigned char *,int)" (?fragment_03@WLD@@QAEXPAEH@Z)

编辑:此外,我正在使用MSVC++。我应该尝试创建一个新的解决方案并导入文件吗?可能会有所帮助,因为我觉得自己别无选择。。。

编辑:这是代码:

#include "WLD.h"
inline void WLD::fragment_03(uchar* location, int frag_num)
{
    // Read the struct into memory and create a temporary pointer
    struct_frag03 temp03;
    memcpy(&temp03, location, sizeof(struct_frag03));
    uchar* temp_p = location;
    // Advance the pointer to the encoded bytes (filename)
    temp_p += sizeof(long) + sizeof(short);
    // Grab the encoded filename and decode it
    uchar* f_filename = new uchar [sizeof(temp03.nameLen + 1)];
    memcpy(f_filename, temp_p, temp03.nameLen + 1);
    decode(f_filename, temp03.nameLen);
    // Add the details about this bitmap to the array
    bmp_array[current_bmp].filename = f_filename;
    bmp_array[current_bmp].nameLength = temp03.nameLen;
    bmp_array[current_bmp].reference03 = frag_num;
    // 0x03 Debug
    //errorLog.OutputSuccess("0x03 Filename: %s", bmp_array[current_bmp].filename);
    //errorLog.OutputSuccess("0x03 Name length: %i",bmp_array[current_bmp].nameLength);
    //errorLog.OutputSuccess("0x03 Reference: %i", bmp_array[current_bmp].reference03);
    // Add the bitmap to the count
    current_bmp++;
}

这里是在WLD类中调用代码的地方:

case 0x03:
    fragment_03(wld + file_pos + sizeof(struct_wld_basic_frag), i);
    break;

这是头文件声明:in(WLD.h):

public:
    inline void fragment_03(uchar* location, int frag_num);

inline表示函数有效地具有内部链接(即,它必须存在于使用它的翻译单元内部)。将函数的定义移动到标头中,或者删除inline

(对于现代编译器来说,inline实际上意味着"使用内部链接"——编译器会在自己有意义的地方内联,而且他们通常比人类做出更好的决策)

EDIT:从技术上讲,标准在这里使用的语言说内联函数具有外部链接;然而,它在标准第3.2节第3段中也提到了An inline function shall be defined in every translation unit in which it is used.,在第5段中也谈到了There can be more than one definition of a ... inline function with external linkage (7.1.2) ... Given such an entity named D defined in more than one translation unit ... each definition of D shall consist of the same sequence of tokens。因此,从技术上讲,您在内联中声明的名称可以从给定的翻译单元外部访问,这样做会导致C++出现未定义的行为。

这与includes无关。您所拥有的是一个链接器错误。Includes都是关于编译的,它需要引用的标识符的声明
您遇到的错误意味着链接器在传递给它的任何对象文件中都找不到函数的定义,该对象文件由其中一个或多个调用。(关于什么是声明、什么是定义以及需要它们做什么,请参阅此答案。)

您需要将编译所有.cpp文件创建的对象文件传递给链接器。如果您正在使用某种IDE,那么如果您将所有.cpp文件添加到项目中,它就应该为您完成这项工作。如果您正在使用makefile,请将所有.cpp文件列为目标的依赖项。如果通过手动调用编译器(然后调用链接器)进行编译,请在同一调用中将所有.cpp文件传递给它。