c ++错误LNK2005和错误LNK1169

时间:2015-04-12 06:22:53

标签: c++ visual-studio-2010 visual-c++

我开始在我的计算机上构建一个项目。在我的计算机上编译的项目,但当我将它复制到另一台计算机时,它有致命的错误(它在visual c ++ express 2010上的工作)。它仍然很小所以我将复制所有的项目。

源文件 - > main.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);
}

源文件 - &gt; List.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);
}

标题文件 - &gt; 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:已在List.obj中定义的“class Products * nodePtr”(?nodePtr @@ 3PAVProducts @@ A)
    错误LNK2005:已在List.obj中定义的“class Products * first”(?first @@ 3PAVProducts @@ A)
    错误LNK1169:找到一个或多个多重定义的符号

1 个答案:

答案 0 :(得分:0)

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

在标题中声明它们:

extern Products* first;

并在源文件中定义它们:

Products* first;

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

相关问题