以下是我的代码中的文件。如果我注释掉所有data.cpp并将函数粘贴到类下的data.h头文件中,它编译得很好。但是当我这样做时它就是分开的我得到了这个错误。
duplicate symbol _salesData in:.../SalesData.build/Objects-normal/x86_64/main.o
.../SalesData.build/Objects-normal/x86_64/Data.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)"
所以我删除main.cpp上的#include“data.h”并注释掉函数调用并编译,但它显然没有按照我想要的那样去做。我不明白我是如何重复符号的。 这是我的文件......
//data.h
#ifndef __SalesData__Data__
#define __SalesData__Data__
#include <iostream>
#include <stdlib.h>
class Data {
public:
//[0] = day DD, [1] = month MM, [2] = year YYYY
float data[32][13][9999];
void newData();
void editData();
float viewData();
}salesData;
#endif /* defined(__SalesData__Data__) */
...
//data.cpp
#include "Data.h"
void Data::editData() {
unsigned short day;
unsigned short month;
unsigned short year;
float dailySales;
printf("\nSelect Day: ");
printf("\n>> ");
std::cin >> day;
printf("\nSelect Month: ");
printf("\n>> ");
std::cin >> month;
printf("\nSelect Year: ");
printf("\n>> ");
std::cin >> year;
printf("\nEnter Daily Sales: ");
printf("\n>> ");
if ((data[day][month][year])) {
std::cin >> dailySales;
data[day][month][year] = dailySales;
}
else {
printf("\nSales have not been recorded for this date. If you wish to input type 'yes' else press any other key");
std::string choice;
std::cin >> choice;
if (choice == "yes") {
newData();
}
}
}
//... same for other class functions
...
//main.cpp
#include <iostream>
#include <stdlib.h>
#include "Data.h"
void selectMain() {
char choice;
while (1) {
printf("Please select an option.");
printf("\n1. Input Data");
printf("\n2. View Data");
printf("\n3. Edit Data");
printf("\n>> ");
std::cin >> choice;
switch (choice) {
case '1':
salesData.newData();
return;
case '2':
salesData.viewData();
return;
case '3':
salesData.editData();
return;
default:
printf("\nInvalid Choice. ");
continue;
}
}
}
int main(int argc, const char * argv[])
{
char endChar;
while (endChar != '`') {
selectMain();
printf("\nPress any key to continue or '`' to end the program.\n");
std::cin >> endChar;
}
printf("\nProgram Ended");
return 0;
}
答案 0 :(得分:2)
问题是导致在类声明后在头文件中定义变量 salesData 的方式。因此,它在 data.cpp 文件和 main.cpp 文件中定义。将 salesData 变量移动到 main.cpp