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

Xcode编译报错:x86_64架构存在2个重复符号

解决Xcode中C++编译的“2 duplicate symbols for architecture x86_64”错误

错误原因

你在main.cpp和Linked.cpp两个源文件中重复定义了全局变量:

time_t t = time(0);
tm* now = localtime(&t);

C++中全局变量的作用域覆盖整个程序,当两个文件编译后链接时,链接器会检测到这两个变量被多次定义,从而抛出重复符号错误。

修复方案

方案一:用extern共享全局变量

  1. 仅在main.cpp中保留变量定义:
// main.cpp
#include "Linked.hpp"
using namespace std;

// 保留全局变量定义
time_t t = time(0);
tm* now = localtime(&t);

int main(){
    // ... 原有代码
}
  1. 在Linked.hpp中添加外部声明,让Linked.cpp可以引用:
// Linked.hpp
#ifndef Linked_hpp
#define Linked_hpp

// ... 已有的头文件包含和类定义
extern time_t t;
extern tm* now;

#endif /* Linked_hpp */
  1. 删除Linked.cpp中的变量定义:
// Linked.cpp
#include "Linked.hpp"

// 移除这两行:time_t t = time(0); tm* now = localtime(&t);
using namespace std;

// ... 原有函数实现

方案二:改为局部变量(更推荐,减少全局依赖)

只有Linked::display函数用到了now,直接将变量移到该函数内部:

void LinkedList::display(Node* head){
    ofstream outputFile ("output.txt");
    Node* list = head;
    
    // 在函数内定义局部变量
    time_t t = time(0);
    tm* now = localtime(&t);
    
    outputFile << "Job ID  " << setw(10) << "Arrival Time  " << setw(10) << "Priority ID  " << endl;
    while(list){
        if (head == nullptr){
            isEmpty(list);
        }
        else{
            outputFile << list->jobID << " " << setw(10) << (now->tm_year + 1900) << "-" << (now->tm_mon +1)  << "-" << now->tm_mday << setw(5) << list->priority_value << endl;
            list = list->next;
        }
    }
}

同时删除main.cpp和Linked.cpp中的全局变量定义。

额外优化提示

  • 你当前的while(!myfile.eof())写法会导致最后一行重复读取,建议修改为:
string line;
while(getline(myfile, line)){
    std::replace(line.begin(), line.end(), ',', ' ');
    stringstream ss(line);
    int job_ID;
    int priority_value;
    int arrival_time;
    int processing_time;
    ss >> job_ID;
    ss >> priority_value;
    ss >> arrival_time;
    ss >> processing_time;
    l.enqueue(&head,job_ID, priority_value,arrival_time,processing_time);
}
  • LinkedList类自身已有head成员变量,main中无需再定义Node* head = nullptr,直接使用l.head即可避免混淆。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 04:40:35