Содержание
- Программа в с++ выдаёт: ошибку обнаружен многократно определенный символ — один или более
- Fatal error lnk1169 обнаружен многократно определенный символ один или более
- Лучший отвечающий
- Вопрос
- фатальная ошибка LNK1169: один или несколько кратно определенных символов, найденных в игровом программировании
- Решение
- Другие решения
- Fatal error lnk1169 обнаружен многократно определенный символ один или более
- Лучший отвечающий
- Вопрос
- фатальная ошибка LNK1169: в игровом программировании обнаружен один или несколько многократно определенных символов
- 6 ответы
Программа в с++ выдаёт: ошибку обнаружен многократно определенный символ — один или более
Причина, указанная Андреем Котоусовым, возможна, но маловероятна. Те, кто линкует в свой экзешник множество библиотек, не задают таких вопросов. Тем более что в современных библиотеках используются namespace’ы, так что столкновения имен обычно не происходит.
А ВЕРОЯТНАЯ причина вот какая. Вы поместили определение функции (подчеркиваю, именно определение, то есть ТЕЛО функции, а не ее декларацию) в *.h файл. Если этому файлу сделан #include только в ОДИН *.cpp файл, то линковка пройдет и линковщик ни на что не пожалуется. Но если этому файлу сделан #include в два или более *.cpp файлов, то после компиляции в каждом из них возникнет та же самая функция. Линковщик выругается, что видит больше одной функции с одним и тем же прототипом. Решения у этой проблемы два: или перенести тело функции в *.cpp файл, оставив в *.h файле только декларацию (прототип) , или оставить функцию на месте, но объявить ее inline.
Тот же самый эффект может получиться не только с функциями, но и с другими объектами. Скажем, для статических членов класса нужно давать определение в *.срр файле, за пределами определения класса. Но если вы поместите это определение в *.h файл, а затем сделаете этому файлу #include в два или более *.cpp файлов, то линковщик выругается, что он видит несколько определений одного и того же символа.
Кстати, Михаил Левин неправ: чтобы получить такую жалобу от линковщика, совершенно не обязательно сдублировать определение ИМЕННО фунции main. Любая функция проканает.
Источник
Fatal error lnk1169 обнаружен многократно определенный символ один или более
Лучший отвечающий
Вопрос
Язык программирования: 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 не должен скрывать переменную от других файлов?
Источник
фатальная ошибка LNK1169: один или несколько кратно определенных символов, найденных в игровом программировании
Я тренировался использовать объектно-ориентированное программирование в C ++, но я продолжаю получать эту ошибку:
Однако, мне кажется, что весь код написан правильно, и эти два целых числа упоминаются только в глобальном заголовке, и все объекты, похоже, наследуются правильно. Однако, как я только что сказал, я новичок в ООП, поэтому мне действительно нужно мнение: Стоит также упомянуть, что я использую allegro 5 для создания бокового шутера.
Решение
Два int переменные определенный в заголовочном файле. Это означает, что каждый исходный файл, который включает заголовок, будет содержать их определение (включение заголовка является чисто текстовым). Конечно, приводит к множественным ошибкам определения.
У вас есть несколько вариантов, чтобы это исправить.
Сделать переменные static ( static int WIDTH = 1024; ). Они будут по-прежнему существовать в каждом исходном файле, но их определения не будут видны за пределами исходного файла.
Превратите их определения в декларации, используя extern ( extern int WIDTH; ) и положить определение в один исходный файл: int WIDTH = 1024; ,
Вероятно, лучший вариант: сделать переменные const ( const int WIDTH = 1024; ). Это делает их static неявно, а также позволяет использовать их в качестве констант времени компиляции, что позволяет компилятору использовать их значение напрямую, а не выдавать код для чтения его из переменной и т. д.
Другие решения
Вы не можете помещать определения переменных в файлы заголовков, так как они будут частью всего исходного файла, в который вы включаете заголовок.
#pragma once просто для защиты от нескольких включений в одном исходном файле, а не от нескольких включений в нескольких исходных файлах.
Вы могли бы объявлять переменные как extern в заголовочном файле, а затем определять их в одном исходном файле. Или же вы можете объявить переменные как const в заголовочном файле, и компилятор и компоновщик будут управлять им.
Источник
Fatal error lnk1169 обнаружен многократно определенный символ один или более
Лучший отвечающий
Вопрос
Язык программирования: 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 не должен скрывать переменную от других файлов?
Источник
фатальная ошибка LNK1169: в игровом программировании обнаружен один или несколько многократно определенных символов
Я тренировался использовать объектно-ориентированное программирование на С++, но я продолжаю получать эту ошибку:
Однако мне кажется, что весь код написан правильно, и два целых числа упоминаются только в глобальном заголовке, и все объекты, похоже, наследуются правильно. Однако, как я только что сказал, я новичок в ООП, поэтому мне действительно нужно мнение: также стоит упомянуть, что я использую allegro 5 для создания бокового шутера.
задан 20 марта ’13, 07:03
6 ответы
Эти два int переменные определенный в заголовочном файле. Это означает, что каждый исходный файл, который включает заголовок, будет содержать их определение (включение заголовка является чисто текстовым). Это, конечно, приводит к множественным ошибкам определения.
У вас есть несколько вариантов исправить это.
Сделайте переменные static ( static int WIDTH = 1024; ). Они по-прежнему будут существовать в каждом исходном файле, но их определения не будут видны за пределами исходного файла.
Превратите их определения в объявления, используя extern ( extern int WIDTH; ) и поместите определение в one исходный файл: int WIDTH = 1024; .
Вероятно, лучший вариант: сделать переменные const ( const int WIDTH = 1024; ). Это делает их static неявно, а также позволяет использовать их в качестве констант времени компиляции, позволяя компилятору использовать их значение напрямую, вместо того, чтобы выдавать код для чтения его из переменной и т. д.
Источник
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:
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

Объясните пожалуйста что не так
-
Вопрос
-
Язык программирования: 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
-
Изменено
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
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
3,3305 gold badges23 silver badges45 bronze badges
asked Oct 4, 2012 at 9:00
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 GrigoreLuchian Grigore
251k63 gold badges454 silver badges619 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 AsotskyDanil Asotsky
1,2414 gold badges24 silver badges29 bronze badges
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
3,3305 gold badges23 silver badges45 bronze badges
asked Oct 4, 2012 at 9:00
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 GrigoreLuchian Grigore
251k63 gold badges454 silver badges619 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 AsotskyDanil Asotsky
1,2414 gold badges24 silver badges29 bronze badges


