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

unreal

0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

1

06.03.2012, 18:36. Показов 59752. Ответов 9

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

код который показан снизу я компилировал в двух программах на visual c++ и dev c++
в dev c++ всё прошло успешно но в visual c++ выдаёт ошибку «fatal error LNK1169: обнаружен многократно определенный символ — один или более».. как решить это ?

C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
 int main()
 {
 int c=7;
 int& d = c; 
 cout <<c;
 system("pause");
 return 0;    
 
 }



0



Эксперт С++

5827 / 3478 / 358

Регистрация: 08.02.2010

Сообщений: 7,448

06.03.2012, 18:45

2

unreal, скорее всего, у тебя в проекте есть еще файл, в котором определена функция main. Выложи сообщение об ошибке полностью



1



unreal

0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

06.03.2012, 20:33

 [ТС]

3

даже так

C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
 int main()
 {
 int c=7;
 //int& d = c; 
 cout << c << endl;
 system("pause");
 return 0;    
 
 }

пишеть ошибку.
MSVCRTD.lib(crtexew.obj) : error LNK2019: ссылка на неразрешенный внешний символ _WinMain@16 в функции ___tmainCRTStartup
visual studioc++azadDebugazad.exe : fatal error LNK1120: 1 неразрешенных внешних элементов

что делать прошу помогите



0



5230 / 3202 / 362

Регистрация: 12.12.2009

Сообщений: 8,112

Записей в блоге: 2

06.03.2012, 20:50

4

unreal, ты проект ни того типа создал. Создай консольное приложение.



1



0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

06.03.2012, 20:52

 [ТС]

5

спс. а какое их отличие ?



0



5230 / 3202 / 362

Регистрация: 12.12.2009

Сообщений: 8,112

Записей в блоге: 2

06.03.2012, 20:54

6

Разные ключи компиляции для консольного и неконсольного приложения.



1



0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

06.03.2012, 21:04

 [ТС]

7

почему в visual c++ не откроет <iostream.h> ?



0



5230 / 3202 / 362

Регистрация: 12.12.2009

Сообщений: 8,112

Записей в блоге: 2

07.03.2012, 08:09

8

Цитата
Сообщение от unreal
Посмотреть сообщение

почему в visual c++ не откроет <iostream.h> ?

Потому что это старый стандарт, сейчас пишут просто <iostream>



1



-=ЮрА=-

Заблокирован

Автор FAQ

07.03.2012, 16:35

9

Цитата
Сообщение от unreal
Посмотреть сообщение

int& d = c;

Цитата
Сообщение от unreal
Посмотреть сообщение

_WinMain@16 в функции ___tmainCRTStartup
visual studioc++azadDebugazad.exe : fatal error LNK1120: 1 неразрешенных внешних элементов

— это означает что по всей видимости ты выбрал тим проекта Win32 вместо Console aplication. Просто создай по новой проект и выбери правильный тип проекта



1



1 / 1 / 0

Регистрация: 05.11.2012

Сообщений: 8

07.11.2012, 20:13

10

Цитата
Сообщение от Nameless One
Посмотреть сообщение

unreal, скорее всего, у тебя в проекте есть еще файл, в котором определена функция main. Выложи сообщение об ошибке полностью

У меня вообще не выдает ошибку только, если 1 файл в проекте.



0



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

machine.h:

#pragma once
#ifndef MACHINE_H
#define MACHINE_H
class Machine {
public:
    char name[50]; // название станка
    float kol; // количество отработанных часов
    float kolH; // количество изготовленных деталей за час

    void TEST(void);
    void TASK2(const Machine* arr, size_t n);
    void INIT(void);
    void SHOW(void);

    Machine();
    Machine(const char* na, float ko, float koH);
    Machine(const Machine& obj);
    ~Machine();
    };

#endif

machine.cpp:

#include <iostream>
#include <string>
#include <fstream>
#include "machine.h"
using namespace std;
float kool = 0;

Machine::Machine() {
    cout << endl << "--------------------------------------------------" << endl;
    cout << "Этот обьект был создан в конструкторе по умолчанию.n";
    strcpy(name, "СтанокВторой");
    kol = 3;
    kolH = 8;
}

Machine::Machine(const char* na, float ko, float koH) {
    cout << endl << "--------------------------------------------------" << endl;
    cout << "Этот обьект был создан в конструкторе с параметрами.n";
    strcpy(name, na);
    kol = ko;
    kolH = koH;
}

Machine::Machine(const Machine& obj) {
    cout << endl << "--------------------------------------------------" << endl;
    cout << "Этот обьект был создан в конструкторе копирования.n";
    strcpy(name, obj.name);
    kol = obj.kol;
    kolH = obj.kolH;
}

void Machine::TEST(void) {
    kool += kol;
}

Machine::~Machine() {
    cout << endl << "--------------------------------------------------" << endl;
    cout << "Удаление объекта деструктором.n";
}

void Machine::SHOW(void) {
    cout << endl << "--------------------------------------------------" << endl;
    cout << "Информация о станке:n";
    cout << "nНазвание станка > " << name;
    cout << "nКоличество отработанных часов > " << kol;
    cout << "nКоличество изготовленных деталей за час > " << kolH;
}

void Machine::INIT(void) {
    cout << endl << "--------------------------------------------------" << endl;
    cout << "Введите данные о станке:n";
    cout << "nНазвание > "; cin >> name;
    cout << "nКоличество отработанных часов > "; cin >> kol;
    cout << "nКоличество изготовленных деталей за час > "; cin >> kolH;
}

void Machine::TASK2(const Machine* arr, size_t n) {
    size_t i_min = 0;
    for (size_t i = 1; i < n; ++i)
        if (arr[i_min].kol > arr[i].kol)
            i_min = i;

    std::cout << arr[i_min].name << std::endl;
}

Source.cpp:

#include <iostream>
#include <string>
#include <fstream>
#include "machine.h"
using namespace std;
float kool = 0;

int main() {
    setlocale(0, "");

    Machine M1("Станок_Большой", 32, 68);
    M1.SHOW();
    Machine M2;

    ofstream fout;
    fout.open("1.txt");
    fout << M1.name << " " << M1.kol << " " << M1.kolH;
    fout.close();

    ifstream fin;
    fin.open("1.txt");
    fin >> M2.name >> M2.kol >> M2.kolH;
    fin.close();

    cout << "nИнформация про станок 2:n";
    M2.SHOW();

    fin.open("1.txt");
    fin.seekg(0);
    cout << "nПотоковый вывод содержания 1.txtn";
    char ch;
    while (fin.get(ch))
        cout << ch;
    cout << "nnВывод законченnn";
    fin.close();

    M1.TEST();
    M2.TEST();
    cout << "Количество отработаных часов (общее): " << kool;

    cout << endl << "--------------------------------------------------" << endl;
    cout << "Заполнение массива экземпляров ma";

    Machine ma[2];
    for (int i = 0; i < 2; i++) {
        cout << "nВвод информации про " << i + 1 << " объект";
        ma[i].INIT();
    }
    for (int i = 0; i < 2; i++) {
        cout << "nВывод информации про " << i + 1 << " объект";
        ma[i].SHOW();
    }

    cout << "nnНазвание станка, который имеет наименьшее количество отработанных часов -->> ";
    ma -> TASK2(ma, 2);

    return 0;
}

Ошибки:

1)
Ошибка  LNK2005 "float kool" (?kool@@3MA) уже определен в machine.obj
2)
Oшибка  LNK1169 обнаружен многократно определенный символ - один или более  ПР 6

I am getting this error:

fatal error LNK1169: one or more multiply defined symbols found

Below are two files containing the code. In file 1, I have the main() function and I am calling the functions which are written in the second file named linklist.cpp.
Thanks for helping in advance.

File 1 — main.cpp

#include "stdafx.h"
# include "linklist.cpp"


int main(int argc, _TCHAR* argv[])
{
    node *link_list2;
    link_list2 = createList(31);
    addFront(link_list2,33);
    printList(link_list2);
    printf("Hello There Omer Obaid khann");
    return 0;
}

File 2 — linklist.cpp

# include "stdafx.h"
# include <stdlib.h>
struct node{
    node * next;
    int nodeValue;

};

node* initNode(int number);
node* createList (int value);
void addFront (node *head, int num );
void deleteFront(node*num);
void destroyList(node *list);
int getValue(node *list);

node*createList (int value)  /*Creates a Linked-List*/
{
    node *dummy_node = (node*) malloc(sizeof (node));
    dummy_node->next=NULL;
    dummy_node->nodeValue = value;
    return dummy_node;
}


void addFront (node *head, int num ) /*Adds node to the front of Linked-List*/
{
    node*newNode = initNode(num);   
    newNode->next = NULL;
    head->next=newNode;
    newNode->nodeValue=num;
}

void deleteFront(node*num)   /*Deletes the value of the node from the front*/
{
    node*temp1=num->next;

    if (temp1== NULL) 
    {
        printf("List is EMPTY!!!!");
    }
    else
    {
        num->next=temp1->next;
        free(temp1);
    }

}

void destroyList(node *list)    /*Frees the linked list*/
{
    node*temp;
    while (list->next!= NULL) 
    {
        temp=list;
        list=temp->next;
        free(temp);
    }
    free(list);
}

int getValue(node *list)    /*Returns the value of the list*/
{
    return((list->next)->nodeValue);
}


void printList(node *list)   /*Prints the Linked-List*/
{

    node*currentPosition;
    for (currentPosition=list->next; currentPosition->next!=NULL; currentPosition=currentPosition->next)  
    {
        printf("%d n",currentPosition->nodeValue);
    }   
    printf("%d n",currentPosition->nodeValue);

}

node*initNode(int number) /*Creates a node*/
{
    node*newNode=(node*) malloc(sizeof (node));
    newNode->nodeValue=number;
    newNode->next=NULL;
    return(newNode);
}

Coding Mash's user avatar

Coding Mash

3,3405 gold badges23 silver badges45 bronze badges

asked Oct 4, 2012 at 9:00

OOkhan's user avatar

I stopped reading after # include "linklist.cpp". Don’t include implementation files in other implementation files. (unless you’re doing bulk-builds, which I doubt). Separate declarations in headers and include those, and keep the definitions in the implementation files.

answered Oct 4, 2012 at 9:01

Luchian Grigore's user avatar

Luchian GrigoreLuchian Grigore

252k64 gold badges457 silver badges621 bronze badges

7

You have two ways to solve your problem:

First is given in answer of Luchian Grigore. Create separate header and include it in main file.

Second one is exclude file linklist.cpp from build using project options.
In other way this file will be build twice: during his own build and during main file build.

However, second way is not good programming style. It is better to create header file.

answered Oct 4, 2012 at 9:13

Danil Asotsky's user avatar

Danil AsotskyDanil Asotsky

1,2414 gold badges23 silver badges29 bronze badges

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?

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

Linker Tools Error LNK1169

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.

unreal

0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

1

06.03.2012, 18:36. Показов 57256. Ответов 9

Метки нет (Все метки)


код который показан снизу я компилировал в двух программах на visual c++ и dev c++
в dev c++ всё прошло успешно но в visual c++ выдаёт ошибку «fatal error LNK1169: обнаружен многократно определенный символ — один или более».. как решить это ?

C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
 int main()
 {
 int c=7;
 int& d = c; 
 cout <<c;
 system("pause");
 return 0;    
 
 }

__________________
Помощь в написании контрольных, курсовых и дипломных работ, диссертаций здесь

0

Эксперт С++

5826 / 3477 / 358

Регистрация: 08.02.2010

Сообщений: 7,448

06.03.2012, 18:45

2

unreal, скорее всего, у тебя в проекте есть еще файл, в котором определена функция main. Выложи сообщение об ошибке полностью

1

unreal

0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

06.03.2012, 20:33

 [ТС]

3

даже так

C++
1
2
3
4
5
6
7
8
9
10
11
#include <iostream>
using namespace std;
 int main()
 {
 int c=7;
 //int& d = c; 
 cout << c << endl;
 system("pause");
 return 0;    
 
 }

пишеть ошибку.
MSVCRTD.lib(crtexew.obj) : error LNK2019: ссылка на неразрешенный внешний символ _WinMain@16 в функции ___tmainCRTStartup
visual studioc++azadDebugazad.exe : fatal error LNK1120: 1 неразрешенных внешних элементов

что делать прошу помогите

0

5225 / 3197 / 362

Регистрация: 12.12.2009

Сообщений: 8,101

Записей в блоге: 2

06.03.2012, 20:50

4

unreal, ты проект ни того типа создал. Создай консольное приложение.

1

0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

06.03.2012, 20:52

 [ТС]

5

спс. а какое их отличие ?

0

5225 / 3197 / 362

Регистрация: 12.12.2009

Сообщений: 8,101

Записей в блоге: 2

06.03.2012, 20:54

6

Разные ключи компиляции для консольного и неконсольного приложения.

1

0 / 0 / 1

Регистрация: 26.02.2012

Сообщений: 118

06.03.2012, 21:04

 [ТС]

7

почему в visual c++ не откроет <iostream.h> ?

0

5225 / 3197 / 362

Регистрация: 12.12.2009

Сообщений: 8,101

Записей в блоге: 2

07.03.2012, 08:09

8

Цитата
Сообщение от unreal
Посмотреть сообщение

почему в visual c++ не откроет <iostream.h> ?

Потому что это старый стандарт, сейчас пишут просто <iostream>

1

-=ЮрА=-

Заблокирован

Автор FAQ

07.03.2012, 16:35

9

Цитата
Сообщение от unreal
Посмотреть сообщение

int& d = c;

Цитата
Сообщение от unreal
Посмотреть сообщение

_WinMain@16 в функции ___tmainCRTStartup
visual studioc++azadDebugazad.exe : fatal error LNK1120: 1 неразрешенных внешних элементов

— это означает что по всей видимости ты выбрал тим проекта Win32 вместо Console aplication. Просто создай по новой проект и выбери правильный тип проекта

1

1 / 1 / 0

Регистрация: 05.11.2012

Сообщений: 8

07.11.2012, 20:13

10

Цитата
Сообщение от Nameless One
Посмотреть сообщение

unreal, скорее всего, у тебя в проекте есть еще файл, в котором определена функция main. Выложи сообщение об ошибке полностью

У меня вообще не выдает ошибку только, если 1 файл в проекте.

0

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;

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

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


Recommended Answers

Please use code tags instead, and watch spaces like in using namespace or else if .

#include<iostream>

using namespace std;

int main()
{
   int age;
   char sex;

   cout<<"please input your age:";

   cout<<"please input your sex (M/F):";
   cin>> age;
   cin>> sex;
   if ( age < 100 …

Jump to Post

The same program works fine with me.
Which OS and compiler (version) are u using?

Jump to Post

There must be some information that you can see that you’re not telling us. How did you set up the project? Are there other files in it? Etc.?

Jump to Post

You can have more files, but as the linker seems to be telling you, you can’t have the same thing defined in more than one place. I don’t suppose you’d care to post all the relevant code?

Jump to Post

All 13 Replies

Member Avatar

16 Years Ago

Please use code tags instead, and watch spaces like in using namespace or else if .

#include<iostream>

using namespace std;

int main()
{
   int age;
   char sex;

   cout<<"please input your age:";

   cout<<"please input your sex (M/F):";
   cin>> age;
   cin>> sex;
   if ( age < 100 )
   {
      cout<<"you are pretty young!n";
   }
   else if ( age ==100 && sex == 'm' )
   {
      cout<<"you are pretty old,and you are male!n";
   }
   else if ( age ==100 && sex == 'f' )
   {
      cout<<"you are pretty old, and u r a female!n";
   }
   else
   {
      cout<<"You are relly old!n";
   }
}

Any problem with this?

Member Avatar

16 Years Ago

Thanks for your reply.But still after took care of spaces,it displays that same error.Please help me.I am new to programming.

#include<iostream>
usingnamespace std;
 
int main() 
{
int age; 
char sex;
 
cout<<"please input your age:"; 
 
cout<<"please input your sex (M/F):";
cin>> age; 
cin>> sex;

if (age < 100){ 
cout<<"you are pretty young!n";
}else if (age == 100 && sex == 'm'){
cout<<"you are pretty old,and you are male!n";
}else if (age == 100 && sex == 'f'){
cout<<"you are pretty old, and u r a female!n";
}else{
cout<<"You are relly old!n";
}
}

Also,i don’t know,how to give programs in code.I used

Member Avatar

~s.o.s~



Team Colleague



Featured Poster

16 Years Ago

The same program works fine with me.
Which OS and compiler (version) are u using?

Member Avatar

16 Years Ago

OS-windows.XP

Compiler-Microsoft VC++ 2005 enterprise edition

Please help me.I couldn’t able to correct that problem.

Member Avatar

16 Years Ago

There must be some information that you can see that you’re not telling us. How did you set up the project? Are there other files in it? Etc.?

Member Avatar

16 Years Ago

Yes,the project has 2 more files with it.I thought in one project we can place more files.

Thanks for the reply and help me.How can i run this file when more that one file is stored in same project.

Member Avatar

16 Years Ago

You can have more files, but as the linker seems to be telling you, you can’t have the same thing defined in more than one place. I don’t suppose you’d care to post all the relevant code?

Member Avatar

16 Years Ago

This is the full error message

Ex2agesex.obj : error LNK2005: _main already defined in Ex1Sum.obj
Ex3currencydollar.obj : error LNK2005: _main already defined in Ex1Sum.obj
C:Documents and SettingsMohan.RBCHRIT7My DocumentsVisual Studio 2005ProjectsOwnProgramsDebugOwnPrograms.exe : fatal error LNK1169: one or more multiply defined symbols found
Build log was saved at «file://c:Documents and SettingsMohan.RBCHRIT7My DocumentsVisual Studio 2005ProjectsOwnProgramsDebugBuildLog.htm»
OwnPrograms — 3 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

How would i set some file as main to run in VC++

Member Avatar

16 Years Ago

Well there you go. You’ve got main defined in more than one file. You can only have one main . Just like the messages are saying. You need a single entry point to your program — decide where it should be.

And again, if you want help with code, it is highly advisable that you post the code you want help with.

Member Avatar

16 Years Ago

Dave thanks for your help and apologize for not asking my question properly.I thought that fatal error would be the problem for my program.

Member Avatar

16 Years Ago

My first program in a project is

#define _CRT_SECURE_NO_DEPRECATE//to take of scanf deprecated warning
#include<stdio.h>
#include<math.h>
//int main()
{
int a,b;
double aSquare,bSquare,sumOfSquare;
printf("input first numbern");
scanf("%d",&a);
printf("input second numbern");
scanf("%d",&b);
printf("sum %dn",a+b);
printf("average %dn",(a+b)/2);
aSquare=sqrt(a);
bSquare=sqrt(b);
sumOfSquare=aSquare+bSquare;
printf("sumOfSquare %fn",sumOfSquare);
}

As you told i have taken off main from it.and my second file is

#include <iostream>
using namespace std;
int main() 
{
int age; 
char sex;
 
cout<<"please input your age:"; 

cout<<"please input your sex (M/F):";
cin>> age; 
cin>> sex;
//cin.ignore(); 
if (age < 100){ 
cout<<"you are pretty young!n";
}else if (age == 100 && sex == 'm'){
cout<<"you are pretty old,and you are male!n";
}else if (age == 100 && sex == 'f'){
cout<<"you are pretty old, and u r a female!n";
}else{
cout<<"You are relly old!n";
}
// cin.get();
}

how can i call the first program in the second one.Displaying two programs output in second file.Please help me.

Member Avatar

16 Years Ago

Make it a function called something other than main , then call it from the other code.

Member Avatar

15 Years Ago

Thanks Dave. Your answer solved my problem as well.


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

Понравилась статья? Поделить с друзьями:
  • Ошибка lnk1123 ошибка при преобразовании в coff
  • Ошибка lnk1123 в c visual studio 2010
  • Ошибка lnk1105 не удается закрыть файл
  • Ошибка lnk1104 не удается открыть файл msvcrtd lib
  • Ошибка lnk1104 не удается открыть файл msvcprtd lib