Меню

Ошибка lnk1169 обнаружен многократно определенный символ один или более

Permalink

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

cpp-docs/docs/error-messages/tool-errors/linker-tools-error-lnk1169.md

Go to file

  • Go to file

  • Copy path


  • Copy permalink

Cannot retrieve contributors at this time

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK1169

Linker Tools Error LNK1169

11/04/2016

LNK1169

LNK1169

e079d518-f184-48cd-8b38-969bf137af54

one or more multiply defined symbols found

The build failed due to multiple definitions of one or more symbols. This error is preceded by error LNK2005.

The /FORCE or /FORCE:MULTIPLE option overrides this error.

I have 3 files:

SilverLines.h
SilverLines.cpp
main.cpp

At SilverLines.cpp I have:

#include "SilverLines.h."

When I don’t do:

#include "SilverLines.h"

at the main.cpp, everything is just fine. The project compiles.

But when I do:

#include "SilverLines.h"

in the main.cpp (Which i need to do), i get these 2 errors:

fatal errors

What’s the problem?

> edit:

As you requested, this is the entire *.h code:

#ifndef SILVER_H
#define SILVER_H

#include <iostream>
#include <algorithm>
#include <iterator>
#include <vector>
#include <string>
#include <map>

using namespace std;

typedef unsigned short int u_s_int;

map<string /*phone*/,string /*company*/> companies; // a map of a phone number and its     company
string findCompany(const string& phoneNum); //Given a phone number, the function     returns the right company

//The Abstract Client Class:

class AbsClient //Abstract Client Class
{
protected:
//string phone_number;
int counter; //CALL DURATION TO BE CHARGED
double charge;
public:
string phone_number; //MOVE TO PROTECTED LATER
void setCharge(double ch) {charge=ch;}
void setCoutner(int count) {counter=count;}
AbsClient(string ph_num): phone_number(ph_num),counter(0), charge(0.0) {} //c'tor     that must be given a phone#.
                                                                            //Initializes the counter and the charge to 0.
virtual void registerCall(string /*phone#*/, int /*minutes*/) = 0; //make a call     and charge the customer
void printReport(string /*phone#*/) const; //prints a minutes report
};

//The Temporary Client Class:

class TempClient : public AbsClient //TempClient class (NO DISCOUNT!) 2.3 NIS PER MINUTE, inherits from ABS
{
private:
string company;
public:
//string company;
TempClient(string ph_num, string cmp_name): AbsClient(ph_num), company(cmp_name) {}
virtual void registerCall(string /*phone#*/, int /*minutes*/); //make a call and     charge the customer
//virtual void printReport(string phone) const {cout << "the number of minutes: " << this->counter << endl;}
};

//The REgistered Client Class:

class RegisteredClient : public AbsClient //RegisteredClient, 10% DISCOUNT! , inherits from ABS
{
protected:
string name;
string id;
long account; //ACCOUNT NUMBER
private:
static const int discount = 10; //STATIC DISCOUNT OF 10% FOR ALL Registered Clients
public:
RegisteredClient(string ph_num, string n, string i, long acc_num):     AbsClient(ph_num), name(n) , id(i) , account(acc_num) {}
virtual void registerCall(string /*phone#*/, int /*minutes*/); //make a call and     charge the customer
//virtual void printReport(string /*phone#*/) const {cout << "the number of     minutes: " << this->counter << endl;}
};

//The VIP Client Class

class VIPClient : public RegisteredClient //VIP Client! X% DISCOUNT! also, inherits from RegisteredClient
{
private: //protected?
int discount; //A SPECIAL INDIVIDUAL DISCOUTN FOR VIP Clients
public:
VIPClient(string ph_num, string n, string i, long acc_num, int X):     RegisteredClient(ph_num,n,i,acc_num), discount(X) {}
virtual void registerCall(string /*phone#*/, int /*minutes*/); //make a call and     charge the customer
//virtual void printReport(string /*phone#*/) const {cout << "the number of     minutes: " << this->counter << endl;}
};

//The SilverLines (the company) class

class SilverLines // The Company Class
{
protected:
vector<AbsClient*> clients;
vector<string> address_book; //DELETE
public:
//static vector<AbsClient*> clients;
//SilverLines();
void addNewClient(string /*phone#*/);
void addNewClient(string /*phone#*/, string /*name*/ , string /*id*/ , u_s_int     /*importance lvl*/ , long /*account#*/);
void registerCall(string /*phone#*/ , int /*call duration*/);
void resetCustomer(string /*phone#*/); //given a phone#, clear the appropriate     customer's data ('charge' and 'counter')
void printReport(string /*phone#*/) const;

~SilverLines(){
    vector<AbsClient*>::iterator it;
    for(it = clients.begin(); it != clients.end(); ++it)
        delete(*it);
}
};

#endif

paercebal’s Answer:

Your code has multiple issues (the

using namespace std;

for one), but the one failing the compilation is the declaration of a global variable in a header:

map<string /*phone*/,string /*company*/> companies;

I’m quite sure most of your sources (main.cpp and SilverLines.cpp, at least) include this header.

You should define your global object in one source file:

// SilverLines.h

extern map<string /*phone*/,string /*company*/> companies;

and then declare it (as extern) in the header:

// global.cpp

extern map<string /*phone*/,string /*company*/> companies;

  • Remove From My Forums

 none

Объясните пожалуйста что не так

  • Вопрос

  • Язык программирования: C

    Среда разработки: Visual Studio 2012 Express

    Не могу понять следующее: я хочу связать между собой main.c и
    count.c(как они выглядят можно найти ниже). 

    В count.c определена переменная num, которая равна
    10. В main.c я хочу вывести переменную
    num
    на экран.

    Если определить num как static int num = 10, то всё работает, однако как только я уберу
    static выходят следующие ошибки: 

    Ошибка
    1 error LNK2005: _b уже определен в count.obj
    c:UsersМОЁ ИМЯdocumentsvisual studio 2012Projectstest_29test_29main.obj
    test_29

    Ошибка
    2 error LNK1169: обнаружен многократно определенный символ — один или более
    c:usersМОЁ ИМЯdocumentsvisual studio 2012Projectstest_29Debugtest_29.exe
    test_29

    Пожалуйста, объясните в чём ошибка. И да, разве static не должен скрывать переменную от других файлов?

    Код, в котором возникает ошибка:

    main.c:

    #include <stdio.h>
    #include "count.c"
    
    main(void)
    {
    	printf("%dn", num);
    }

    count.c:

    int num = 10;

Ответы

  • #include — это простая текстовая подстановка. То есть у Вас получается:
    main.c:

    #include <stdio.h>
    int num = 10;
    
    main(void)
    {
    	printf("%dn", num);
    }

    count.c:

    int num = 10;

    То есть, оба модуля определяют внешнюю переменную с одним и тем же именем, что и приводит к ошибке.
    При использовании static, оба модуля объявляют свою собственную переменную num, недоступную другому модулю.

    • Помечено в качестве ответа

      11 января 2014 г. 18:37

    • Снята пометка об ответе
      iTiPo
      11 января 2014 г. 19:12
    • Помечено в качестве ответа
      Taras KovalenkoBanned
      12 января 2014 г. 13:45

  • > А разве если мы подставили текст из count.c он не должен далее игнорироваться(файл)?

    Если не ошибаюсь, компилятор пройдётся по всем файлам и скомпилирует весь код, независимо от того, был ли он вставлен уже куда-то.

    Чтобы избежать повторных вставок-комплиляций, используются
    Include guard.

    • Помечено в качестве ответа
      Taras KovalenkoBanned
      12 января 2014 г. 13:45

  • Объект из другого модуля можно использовать, если повторить его объявление с модификатором extern. Вот так может выглядеть модуль main.c:

    #include <stdio.h>
    extern int num; // инициализация не учитывается
    
    void main()
    {
        ...
    }

    Включать директивой include файлы исходного кода нельзя, т.к. это приведет к многократной компиляции их кода.

    • Изменено
      kosuke904
      13 января 2014 г. 5:18
    • Помечено в качестве ответа
      iTiPo
      13 января 2014 г. 7:55

I have this:

a.h:

class a
{
}
void func(){} //some golobal function

b.h:

include "a.h"
class b : public a
{
}

b.cpp:

#include "b.h"

I get the error:

error LNK1169: one or more multiply defined symbols found

I think I get the error because global function defined twice. I try to put extern before the function but is doesnt work. I use also #ifndef.. and I still get error. How can solve this problem?

Biffen's user avatar

Biffen

6,1776 gold badges30 silver badges35 bronze badges

asked Jun 10, 2014 at 9:47

user11001's user avatar

4

You have either only to declare the function in header a.h and define it in some cpp module or define it as an inline function. For example

inline void func(){} 

Otherwise the function will be defined as many times as there are cpp modules that include either header a.h or b.h.

answered Jun 10, 2014 at 9:50

Vlad from Moscow's user avatar

Vlad from MoscowVlad from Moscow

286k23 gold badges178 silver badges322 bronze badges

5

I have this:

a.h:

class a
{
}
void func(){} //some golobal function

b.h:

include "a.h"
class b : public a
{
}

b.cpp:

#include "b.h"

I get the error:

error LNK1169: one or more multiply defined symbols found

I think I get the error because global function defined twice. I try to put extern before the function but is doesnt work. I use also #ifndef.. and I still get error. How can solve this problem?

Biffen's user avatar

Biffen

6,1776 gold badges30 silver badges35 bronze badges

asked Jun 10, 2014 at 9:47

user11001's user avatar

4

You have either only to declare the function in header a.h and define it in some cpp module or define it as an inline function. For example

inline void func(){} 

Otherwise the function will be defined as many times as there are cpp modules that include either header a.h or b.h.

answered Jun 10, 2014 at 9:50

Vlad from Moscow's user avatar

Vlad from MoscowVlad from Moscow

286k23 gold badges178 silver badges322 bronze badges

5

Hi ULARbro,

Welcome to MSDN forum.

>> Fatal error
LNK1169

## This error is preceded by error
LNK2005. Generally, this error means you have broken the one definition rule, which allows only one definition for any used template, function, type, or object in a given object file, and only one definition across the entire executable for externally visible
objects or functions.

Do you meet this error when you are running test project? And does your project build/debug well without any error?

According to the official document,  You could refer to below possible causes and for
solutions please refer to this link
Possible causes and solutions.

(1) Check if one of your header file defines a variable and maybe include this header file in more than one source file in your project.

(2) This error can occur when a header file defines a function that isn’t inline. If you include this header file in more than one source file, you get multiple definitions of the function in the executable.

(3) This error can also occur if you define member functions outside the class declaration in a header file.

(4) This error can occur if you link more than one version of the standard library or CRT.

(5) This error can occur if you mix use of static and dynamic libraries when you use the /clr option

(6) This error can occur if the symbol is a packaged function (created by compiling with /Gy)
and it was included in more than one file, but was changed between compilations. 

(7)
This error can occur if the symbol is defined differently in two member objects in different libraries, and both member objects are used. One way to fix this issue when the libraries are statically linked is to use the member object from only one library,
and include that library first on the linker command line. 

(8)
This error can occur if an extern const variable is defined twice, and has a different value in each definition. 

(9) This error can occur if you use uuid.lib in combination with other .lib files that define GUIDs (for example, oledb.lib and adsiid.lib).

There are some similar issues and maybe helpful.

LNK1169 and LNK2005 Errors.

Fatal error LNK1169: one or more multiply defined symbols found in game programming.

Fatal error LNK1169: one or more multiply defined symbols found.

Hope all above could help you.

Best Regards,

Tianyu


MSDN Community Support
Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
MSDN Support, feel free to contact MSDNFSF@microsoft.com.

  • Proposed as answer by

    Friday, December 13, 2019 9:31 AM

Hi ULARbro,

Welcome to MSDN forum.

>> Fatal error
LNK1169

## This error is preceded by error
LNK2005. Generally, this error means you have broken the one definition rule, which allows only one definition for any used template, function, type, or object in a given object file, and only one definition across the entire executable for externally visible
objects or functions.

Do you meet this error when you are running test project? And does your project build/debug well without any error?

According to the official document,  You could refer to below possible causes and for
solutions please refer to this link
Possible causes and solutions.

(1) Check if one of your header file defines a variable and maybe include this header file in more than one source file in your project.

(2) This error can occur when a header file defines a function that isn’t inline. If you include this header file in more than one source file, you get multiple definitions of the function in the executable.

(3) This error can also occur if you define member functions outside the class declaration in a header file.

(4) This error can occur if you link more than one version of the standard library or CRT.

(5) This error can occur if you mix use of static and dynamic libraries when you use the /clr option

(6) This error can occur if the symbol is a packaged function (created by compiling with /Gy)
and it was included in more than one file, but was changed between compilations. 

(7)
This error can occur if the symbol is defined differently in two member objects in different libraries, and both member objects are used. One way to fix this issue when the libraries are statically linked is to use the member object from only one library,
and include that library first on the linker command line. 

(8)
This error can occur if an extern const variable is defined twice, and has a different value in each definition. 

(9) This error can occur if you use uuid.lib in combination with other .lib files that define GUIDs (for example, oledb.lib and adsiid.lib).

There are some similar issues and maybe helpful.

LNK1169 and LNK2005 Errors.

Fatal error LNK1169: one or more multiply defined symbols found in game programming.

Fatal error LNK1169: one or more multiply defined symbols found.

Hope all above could help you.

Best Regards,

Tianyu


MSDN Community Support
Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
MSDN Support, feel free to contact MSDNFSF@microsoft.com.

  • Proposed as answer by

    Friday, December 13, 2019 9:31 AM

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка lo на весах тефаль
  • Ошибка lnk1168 не удается открыть exe для записи