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

Windows下可正常编译的C++代码在Linux g++中报重声明错误

解决Linux下g++编译node* link重定义错误的问题

嘿,这个问题我碰到过好几次啦!你的代码在Windows的Codelite里用g++能正常跑,但到Linux下编译就报错,提示‘node* link’ redeclared as different kind of symbol,其实原因很简单:

Linux系统的标准库(准确说是unistd.h头文件里)已经有一个名为link的系统函数了,它的作用是创建文件硬链接。你在全局作用域声明的node* link和这个系统函数重名了,Linux下的g++会严格检测这种命名冲突,而Windows系统里没有这个同名的系统函数,所以不会触发错误。

给你几个可行的解决办法:

  • 改个变量名(最推荐):
    直接把全局变量link换成别的名字,比如my_link或者list_head,彻底避开冲突。修改后的代码示例:

    #include <iostream>
    #include <cstdlib>
    using std::cout;
    using std::endl;
    struct node {
        int i;
        node* next;
        node(int x, node* t) {
            i = x;
            next = t;
        }
    };
    node *my_link; // 重命名后的变量
    int main() {
        cout << "Yes!" << endl;
        return 0;
    }
    
  • 把变量改成局部的:
    不要在全局作用域声明link,把它放到main函数里作为局部变量,这样就不会和全局作用域的系统函数冲突了:

    #include <iostream>
    #include <cstdlib>
    using std::cout;
    using std::endl;
    struct node {
        int i;
        node* next;
        node(int x, node* t) {
            i = x;
            next = t;
        }
    };
    int main() {
        node *link; // 局部变量,作用域仅限main函数内
        cout << "Yes!" << endl;
        return 0;
    }
    
  • 用命名空间隔离:
    如果你特别想用link这个名字,可以把你的结构体和变量放到自定义的命名空间里,和系统的link函数划清界限:

    #include <iostream>
    #include <cstdlib>
    using std::cout;
    using std::endl;
    namespace my_list {
        struct node {
            int i;
            node* next;
            node(int x, node* t) {
                i = x;
                next = t;
            }
        };
        node *link;
    }
    int main() {
        cout << "Yes!" << endl;
        return 0;
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.25 08:15:18