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

C++迁移函数至新文件后出现multiple definition错误求助

解决C++函数剪切后出现的多重定义错误

问题根源

你直接在example.cpp中#include "utils.cpp"是错误操作。C++里.cpp是独立编译单元,会被单独编译为目标文件。当你include .cpp文件时,相当于把该文件的代码完整复制到当前文件中,之后utils.cpp本身又会被单独编译一次——最终链接阶段,example.o和utils.o中都存在std_dev和mean的定义,链接器无法确定使用哪一份,因此抛出multiple definition错误。

正确操作步骤

  1. 创建头文件utils.h,存放函数声明
    头文件用于对外暴露函数接口,同时用头文件保护防止重复声明:

    #ifndef UTILS_H
    #define UTILS_H
    
    #include <vector>
    #include <cstdint> // 适配uint类型
    
    double std_dev(std::vector<double> Mean, std::vector<double> Mean2, int n, int i);
    float mean(const float* x, uint n);
    
    #endif
    
  2. 在utils.cpp中实现函数并包含头文件
    把剪切过来的函数实现放在utils.cpp里,同时引入头文件确保声明与实现一致:

    #include "utils.h"
    #include <cmath> // 引入sqrt、pow所需的头文件
    
    double std_dev(std::vector<double> Mean, std::vector<double> Mean2, int n,int i){
        if (n==0){
            return 0;
        } else{
            return sqrt((Mean2.at(n) - pow(Mean.at(n),2))/i);
        }
    }
    
    float mean(const float* x, uint n){
        float sum = 0;
        for (int i = 0; i < n; i ++)
            sum += x[i];
        return sum / n;
    }
    
  3. 修改example.cpp的引入方式
    移除#include "utils.cpp",替换为包含头文件:

    #include "utils.h"
    
    // 保留example.cpp原有业务代码,无需再定义std_dev和mean
    
  4. 检查编译配置(以CMake为例)
    确保utils.cpp被加入编译目标,比如在CMakeLists.txt中:

    add_executable(你的项目名 example.cpp utils.cpp)
    

额外注意事项

  • 禁止直接include .cpp文件,这会导致代码重复编译、链接冲突,还会增加编译耗时。
  • 头文件仅存放声明(函数、类、宏等),实现代码必须放在对应的.cpp文件中。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 19:35:37