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

Windows11下CLion中Ninja编译重复定义报错的解决方法

问题描述

我是一名刚接触C语言的学生,在Windows11系统搭配CLion 2022.3.1开发时遇到编译报错,朋友运行同一程序无此问题。已尝试更新Windows、CLion及更换安装目录,问题仍未解决。

报错日志如下:

"C:\Program Files\JetBrains\CLion 2022.3.1\bin\cmake\win\bin\cmake.exe" --build "C:\Users\pablo\OneDrive\Bureau\MALAISE\info\C bebou\e\ProjectPart1\cmake-build-debug" --target ProjectPart1 -j 6
[1/1] Linking C executable ProjectPart1.exe
FAILED: ProjectPart1.exe 
cmd.exe /C "cd . && C:\PROGRA~1\JETBRA~1\CLION2~1.1\bin\mingw\bin\gcc.exe -g  CMakeFiles/ProjectPart1.dir/main.c.obj CMakeFiles/ProjectPart1.dir/shapes.c.obj -o ProjectPart1.exe -Wl,--out-implib,libProjectPart1.dll.a -Wl,--major-image-version,0,--minor-image-version,0  -lkernel32 -luser32 -lgdi32 -lwinspool -lshell32 -lole32 -loleaut32 -luuid -lcomdlg32 -ladvapi32 && cd ."
C:\Program Files\JetBrains\CLion 2022.3.1\bin\mingw\bin/ld.exe: CMakeFiles/ProjectPart1.dir/shapes.c.obj:C:/Users/pablo/OneDrive/Bureau/MALAISE/info/C bebou/e/ProjectPart1/shapes.h:4: multiple definition of `global_id'; CMakeFiles/ProjectPart1.dir/main.c.obj:C:/Users/pablo/OneDrive/Bureau/MALAISE/info/C bebou/e/ProjectPart1/shapes.h:4: first defined here
collect2.exe: error: ld returned 1 exit status
ninja: build stopped: subcommand failed.
解决方法

报错核心是**global_id被多次定义**,原因是你在shapes.h头文件里直接定义了这个全局变量,当main.c和shapes.c都包含这个头文件时,每个源文件编译后都会生成一份global_id的定义,链接时就会冲突。

解决步骤:

  • 在shapes.h里只声明变量,不要定义:
    // shapes.h
    extern int global_id; // 声明变量,告诉编译器这个变量在其他地方定义
    
  • 在shapes.c里定义这个变量:
    // shapes.c
    int global_id = 0; // 实际定义变量,只在一个源文件里写
    
  • 重新编译项目即可。

注意:头文件里只能放声明(函数声明、变量extern声明、宏定义、结构体/枚举类型定义),不要放变量的实际定义或者函数的实现,否则只要多个源文件包含这个头文件,就会出现重复定义的链接错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.21 22:52:50