C++ 错误LNK2005和错误LNK1169

c++ error LNK2005 and error LNK1169

本文关键字:错误 LNK1169 LNK2005 C++      更新时间:2023-10-16

我开始在我的电脑上构建一个项目。 该项目在我的计算机上编译,但是当我将其复制到另一台计算机上时,它出现了致命错误(它在Visual C ++ Express 2010上的工作)。 它仍然很小,所以我将复制所有项目。

源文件>主.cpp:

#include <iostream>
#include <string>
using namespace std;
#include "List.h"
void products_menu(){
    return;
}
void stores_menu(){
    return;
}
void costumers_menu(){
    return;
}
int main(){
    int option;
    Products a;
    do{
        cin>>option;
        if(option==1)
            products_menu();
            //option funcion
        if(option==2)
            stores_menu();
            //option funcion
        if(option==3)
            costumers_menu();
            //option funcion
    }while(option!=4);
}

源文件>列表.cpp:

#include <iostream>
#include <string>
using namespace std;
#include "List.h"
void products_menu(){
    return;
}
void stores_menu(){
    return;
}
void costumers_menu(){
    return;
}
int main(){
    int option;
    Products a;
    do{
        cin>>option;
        if(option==1)
            products_menu();
            //option funcion
        if(option==2)
            stores_menu();
            //option funcion
        if(option==3)
            costumers_menu();
            //option funcion
    }while(option!=4);
}

头文件->List.h:

#pragma once
#ifndef LIST_H
#define LIST_H
#include <string>
using namespace std;
class Products{
    private:
        typedef struct node{
            int id;
            string name;
            int price;
            node* next;
        };
        //typedef struct node* nodePtr;
        //nodePtr head;
    public:
        Products();
        //~Products();
        void addProduct(int id, string& name, int price);
        void updateNameProduct(int id, string& oldName, string& newName);
        void updatePriceProduct(int id, int oldPrice, int newPrice);
        void printProducts();//
    };
Products* first;
Products* nodePtr;
#endif

这是它给我的错误:

错误 LNK2005:"类产品 * 节点Ptr"(?nodePtr@@3PAVProducts@@A)已在 List.obj
中定义 错误 LNK2005:"类产品 * 优先"(?first@@3PAVProducts@@A)已在 List.obj
中定义 错误 LNK1169:找到一个或多个乘法定义的符号

如果必须使用全局变量(这通常是一个坏主意),则无法在标头中定义它们。它们受"一个定义规则"的约束,因此只能在一个源文件中有一个定义。

在标头中声明它们:

extern Products* first;

并在源文件中定义它们:

Products* first;

但听起来你想要的东西更像是注释掉的声明:一个指向第一个node的指针,作为Products类的成员,没有奇怪的全局变量。