这是我的代码中的文件。如果我注释掉所有 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;
}
最佳答案
问题是因为您在类声明后在头文件中定义变量 salesData 的方式。因此,它在 data.cpp 文件和您的 main.cpp 文件中都有定义。将 salesData 变量移动到 main.cpp
关于c++ - 无法分离头文件和 cpp 文件(包含错误和代码),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21293476/