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共享全局变量
- 仅在
main.cpp中保留变量定义:
// main.cpp #include "Linked.hpp" using namespace std; // 保留全局变量定义 time_t t = time(0); tm* now = localtime(&t); int main(){ // ... 原有代码 }
- 在
Linked.hpp中添加外部声明,让Linked.cpp可以引用:
// Linked.hpp #ifndef Linked_hpp #define Linked_hpp // ... 已有的头文件包含和类定义 extern time_t t; extern tm* now; #endif /* Linked_hpp */
- 删除
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
相关产品推荐
相关产品推荐

