You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

调用嵌套命名空间MRSW::Core::multiply函数出现未定义引用错误

嵌套命名空间函数调用出现未定义引用的问题解决

错误信息

D:/GitHub/MRSW/test/test_core.cpp:23: undefined reference to `MRSW::Core::multiply(unsigned long long, unsigned long long)'
collect2.exe: error: ld returned 1 exit status

问题根源与修复步骤

1. bit_operation.cpp 存在语法错误(多余闭合大括号)

你的bit_operation.cpp末尾多了一个无关的},导致函数定义的命名空间归属错误,链接器无法匹配函数声明与实现:

错误代码片段:

#include "../inc/type_define.hpp"
#include "../inc/core/bit_operation.hpp"
namespace MRSW::Core{
        UInt128_s multiply(UInt64 A,UInt64 B)
        { 
        }
    }
// 这个多余的}必须删除
}

修正后代码:

#include "../inc/type_define.hpp"
#include "../inc/core/bit_operation.hpp"

namespace MRSW::Core{
    UInt128_s multiply(UInt64 A,UInt64 B)
    { 
        // 补全乘法实现与返回逻辑,示例如下:
        __uint128_t product = (__uint128_t)A * B;
        UInt128_s result;
        result.r_low = static_cast<UInt64>(product);
        result.r_high = static_cast<UInt64>(product >> 64);
        return result;
    }
}

2. multiply函数缺少返回值

原函数体为空,没有返回声明的UInt128_s类型值,这会导致未定义行为,同时也会让链接器对函数实现的识别出现异常,必须补全返回逻辑。

3. test.cpp的两处错误

  • .cpp文件不需要#pragma once(这是头文件保护指令),直接删除;
  • 使用cout时未加std::前缀,编译会报错,需改为std::cout或添加using namespace std;(源文件中可使用,头文件不推荐)。

修正后的test.cpp核心片段:

#include <iostream>
#include "../inc/core/bit_operation.hpp"

bool areEqual(UInt64 a, UInt64 b) {
    return (a == b);
}

bool test_multiply(void){
    UInt64 A = 0xFFFFFFFFFFFFFFFF;
    UInt64 B = 0x2;
    UInt64 e_low = 0xFFFFFFFFFFFFFFFE;
    UInt64 e_high = 0x1;
    bool status = false;
    UInt128_s results = {0,0};

    results = MRSW::Core::multiply(A, B);
    if (areEqual(results.r_low, e_low))
    {
        std::cout << "Bit operation Multiply : Pass" << std::endl;
    }
    else
    {
        std::cout << "Bit operation Multiply : Failed" << std::endl;
        return status;
    }
    
    if (areEqual(results.r_high, e_high))
    {
        std::cout << "Bit operation Multiply : Pass" << std::endl;
    }
    else
    {
        std::cout << "Bit operation Multiply : Failed" << std::endl;
        return status;
    }

    return true;
}

4. 编译链接需包含所有源文件

确保编译时将bit_operation.cpp和test.cpp都纳入编译流程,比如使用g++命令:

g++ test.cpp ../inc/core/bit_operation.cpp -o test

如果用IDE开发,要把bit_operation.cpp添加到项目的源文件列表中,否则链接器找不到函数的实现代码。


内容的提问来源于stack exchange,提问作者ras red2004

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 01:44:53