Я тренировался использовать объектно-ориентированное программирование в C ++, но я продолжаю получать эту ошибку:
1>main.obj : error LNK2005: "int WIDTH" (?WIDTH@@3HA) already defined in GameObject.obj
1>main.obj : error LNK2005: "int HEIGHT" (?HEIGHT@@3HA) already defined in GameObject.obj
1>Spaceship.obj : error LNK2005: "int WIDTH" (?WIDTH@@3HA) already defined in GameObject.obj
1>Spaceship.obj : error LNK2005: "int HEIGHT" (?HEIGHT@@3HA) already defined in GameObject.obj
1>C:Usersteddocumentsvisual studio 2010ProjectsfullSpaceDebugfullSpace.exe : fatal error LNK1169: one or more multiply defined symbols found
Однако, мне кажется, что весь код написан правильно, и эти два целых числа упоминаются только в глобальном заголовке, и все объекты, похоже, наследуются правильно. Однако, как я только что сказал, я новичок в ООП, поэтому мне действительно нужно мнение: Стоит также упомянуть, что я использую allegro 5 для создания бокового шутера.
Это код:
(главный):
#include <allegro5/allegro.h>
#include <allegro5/allegro_image.h>
#include <allegro5/allegro_primitives.h>
#include <allegro5/allegro_font.h>
#include <allegro5allegro_ttf.h>
#include <allegro5allegro_audio.h>
#include <allegro5allegro_acodec.h>
#include <list>#include "GameObject.h"#include "Spaceship.h"#include "Globals.h"//controls
bool keys[] = {false, false, false, false, false};
enum KEYS{UP, DOWN, LEFT, RIGHT, SPACE};
//globals
Spaceship *ship;
std::list <GameObject *> objects;
std::list <GameObject *>::iterator iter;
std::list <GameObject *>::iterator iter2;//prototypes//main function
int main(int argc, char **argv)
{
//shell variables
bool done = false;
bool render = false;
float gameTime = 0;
int frames = 0;
int gameFPS = 0;
//project variables
ship = new Spaceship();ALLEGRO_BITMAP *shipImage = NULL;
ALLEGRO_BITMAP *cometImage= NULL;
ALLEGRO_BITMAP *explImage = NULL;
ALLEGRO_BITMAP *bgImage = NULL;
ALLEGRO_BITMAP *mgImage = NULL;
ALLEGRO_BITMAP *plImage = NULL;
ALLEGRO_BITMAP *mgImage2 = NULL;
ALLEGRO_BITMAP *fgImage = NULL;
ALLEGRO_BITMAP *titleImage= NULL;
ALLEGRO_BITMAP *lostImage = NULL;//allegro variables
ALLEGRO_DISPLAY *display = NULL;
ALLEGRO_EVENT_QUEUE *event_queue = NULL;
ALLEGRO_TIMER *timer;
ALLEGRO_FONT *font18;//initiate variables
if(!al_init())
return -1;
display = al_create_display(WIDTH, HEIGHT);
if(!display)
return -1;
//addon installation
al_install_keyboard();
al_init_image_addon();
al_init_font_addon();
al_init_ttf_addon();
al_init_primitives_addon();
al_install_audio();
al_init_acodec_addon();
//project init
font18 = al_load_font("arial.ttf", 18, 0);
al_reserve_samples(15);bgImage = al_load_bitmap("layer1.png");
mgImage = al_load_bitmap("layer2.png");
plImage = al_load_bitmap("starMG.png");
mgImage2 = al_load_bitmap("layer3.png");
fgImage = al_load_bitmap("layer4.png");shipImage = al_load_bitmap("spaceship.png");
al_convert_mask_to_alpha(shipImage, al_map_rgb(255, 0, 255));cometImage = al_load_bitmap("asteroid-1-96.png");
explImage = al_load_bitmap("explosion_3_40_128.png");
titleImage = al_load_bitmap("Shooter_Title.png");
lostImage = al_load_bitmap("Shooter_Lose.png");//object init
ship->init(shipImage);//iter list
objects.push_back(ship);srand(time(NULL));
//timer init and startup
event_queue = al_create_event_queue();
timer = al_create_timer(1.0 / 60);
al_register_event_source(event_queue, al_get_timer_event_source(timer));
al_register_event_source(event_queue, al_get_keyboard_event_source());
al_start_timer(timer);
gameTime = al_current_time();
while(!done)
{
ALLEGRO_EVENT ev;
al_wait_for_event(event_queue, &ev);
//input
if(ev.type == ALLEGRO_EVENT_KEY_DOWN)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT] = true;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT] = true;
break;
case ALLEGRO_KEY_UP:
keys[UP] = true;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN] = true;
break;
case ALLEGRO_KEY_SPACE:
keys[SPACE] = true;
break;}
} else if(ev.type == ALLEGRO_EVENT_KEY_UP)
{
switch(ev.keyboard.keycode)
{
case ALLEGRO_KEY_ESCAPE:
done = true;
break;
case ALLEGRO_KEY_LEFT:
keys[LEFT] = false;
break;
case ALLEGRO_KEY_RIGHT:
keys[RIGHT] = false;
break;
case ALLEGRO_KEY_UP:
keys[UP] = false;
break;
case ALLEGRO_KEY_DOWN:
keys[DOWN] = false;
break;
case ALLEGRO_KEY_SPACE:
keys[SPACE] = false;
break;
}
}else if (ev.type == ALLEGRO_EVENT_TIMER)
{
render = true;
//fps
frames++;
if(al_current_time() - gameTime >= 1)
{
gameTime = al_current_time();
gameFPS = frames;
frames = 0;
}
//shipUpdate
if(keys[UP])
ship ->moveUp();
else if(keys[DOWN])
ship ->moveDown();
else
ship->resetAnim(1);
if(keys[LEFT])
ship ->moveLeft();
else if(keys[RIGHT])
ship -> moveRight();
else
ship ->resetAnim(0);
}
//render
if(render && al_is_event_queue_empty(event_queue))
{
render = false;
//begin render
for(iter = objects.begin(); iter != objects.end(); ++iter)
(*iter)->render();//Flip Buffers
al_flip_display();
al_clear_to_color(al_map_rgb(0,0,0));
}
}
//destroy objects//visual objects
al_destroy_bitmap(cometImage);
for(iter = objects.begin(); iter != objects.end(); ++iter)
(*iter)->destroy(shipImage);
iter = objects.erase(iter);
al_destroy_bitmap(explImage);
al_destroy_bitmap(bgImage);
al_destroy_bitmap(mgImage);
al_destroy_bitmap(fgImage);
al_destroy_bitmap(titleImage);
al_destroy_bitmap(lostImage);
//audio objects
/*
al_destroy_sample(shot);
al_destroy_sample(boom);
al_destroy_sample(song);
al_destroy_sample_instance(songInstance);
*///shell objects
al_destroy_font(font18);
al_destroy_timer(timer);
al_destroy_event_queue(event_queue);
al_destroy_display(display);
return 0;
}
(Globals.h):
#pragma once
int WIDTH = 1024;
int HEIGHT = 800;
enum ID{PLAYER, ENEMY, BULLET, BORDER, MISC};
enum STATES{TITLE, PLAYING, LOST};
(GameObject.h):
#pragma once#include "Globals.h"#include <iostream>
#include <allegro5/allegro5.h>
#include <allegro5/allegro_primitives.h>class GameObject
{
private:
int ID;
bool alive;
bool collidable;
protected:
float x;
float y;
float velX;
float velY;
int dirX;
int dirY;
int boundX;
int boundY;
int maxFrame;
int curFrame;
int frameCount;
int frameDelay;
int frameWidth;
int frameHeight;
int animationColumns;
int animationDirection;
ALLEGRO_BITMAP *image;
public:
GameObject();
void virtual destroy(ALLEGRO_BITMAP *image);
void init(float x, float y, float velX, float velY, int dirX, int dirY, int boundX, int boundY);
void virtual update();
void virtual render();
float getX() {return x;}
float getY() {return y;}
void setX(float x) {GameObject::x = x;}
void setY(float y) {GameObject::y = y;}
int getBoundX() {return boundX;}
int getBoundY() {return boundY;}
int getID() {return ID;}
void setID(int ID) {GameObject::ID = ID;}
bool getAlive() {return alive;}
void setAlive(bool alive) {GameObject::alive = alive;}
bool getCollidable() {return collidable;}
void setCollidable(bool collidable) {GameObject::collidable = collidable;}
bool checkCollisions(GameObject *otherObject);
void virtual collided(int objectID);
bool collidableCheck();
};
(GameObject.cpp):
#include "GameObject.h"
GameObject::GameObject()
{
x = 0;
y = 0;
velX = 0;
velY = 0;
dirX = 0;
dirY = 0;
boundX = 0;
boundY = 0;
maxFrame = 0;
curFrame = 0;
frameCount = 0;
frameDelay = 0;
frameWidth = 0;
frameHeight = 0;
animationColumns = 0;
animationDirection = 0;
image = NULL;
alive = true;
collidable = true;
}
void GameObject::destroy(ALLEGRO_BITMAP *image)
{
if(image != NULL)
al_destroy_bitmap(image);
}
void GameObject::init(float x, float y, float velX, float velY, int dirX, int dirY, int boundX, int boundY)
{
GameObject::x = x;
GameObject::y = y;
GameObject::velX = velX;
GameObject::velY = velY;
GameObject::dirX = dirX;
GameObject::dirY = dirY;
GameObject::boundX = boundX;
GameObject::boundY = boundY;
}
void GameObject::update()
{
x += velX*dirX;
y += velY*dirY;
}
void GameObject::render()
{
}
bool GameObject::checkCollisions(GameObject *otherObject)
{
float oX = otherObject->getX();
float oY = otherObject->getY();
int obX = otherObject->getBoundX();
int obY = otherObject->getBoundY();
if(x + boundX > oX - obX &&
x - boundX < oX + obX &&
y + boundY > oY - obY &&
y - boundY < oY + obY
)
return true;
else
return false;
}
void GameObject::collided(int objectID)
{
}
bool GameObject::collidableCheck()
{
return alive && collidable;
}
(SpaceShip.h):
#pragma once
#include "GameObject.h"
class Spaceship : public GameObject
{
private :
int lives;
int score;
int animationRow;
public :
Spaceship();
void destroy(ALLEGRO_BITMAP *image);
void init(ALLEGRO_BITMAP *image = NULL);
void update();
void render();
void moveUp();
void moveDown();
void moveLeft();
void moveRight();
void resetAnim(int pos);
int getLives(){return lives;}
int getScore() {return score;}
void looseLife() {lives--;}
void addPoint() {score++;}
void collide(int objectID);};
(SpaceShip.cpp):
#include "Spaceship.h"
Spaceship::Spaceship()
{}
void Spaceship::destroy(ALLEGRO_BITMAP *image)
{
GameObject::destroy(image);
}
void Spaceship::init(ALLEGRO_BITMAP *image)
{
GameObject::init(20, 200, 6, 6, 0, 0, 10, 12);
setID(PLAYER);
setAlive(true);
lives = 3;
score = 0;
maxFrame = 3;
curFrame = 0;
frameWidth = 46;
frameHeight = 41;
animationColumns = 3;
animationDirection = 1;
animationRow = 1;
if(image != NULL)
{
Spaceship::image = image;
}
}
void Spaceship::update()
{
GameObject::update();
if(x < 0)
x=0;
else if ( x > WIDTH)
x = WIDTH;
if(y < 0)
y = 0;
else if (y > HEIGHT)
y = HEIGHT;
}
void Spaceship::render()
{
GameObject::render();
int fx = (curFrame % animationColumns) *frameWidth;
int fy = animationRow *frameHeight;
al_draw_bitmap_region(image, fx, fy, frameWidth, frameHeight,
x - frameWidth /2, y - frameHeight /2, 0);
}
void Spaceship::moveUp()
{
animationRow = 0;
dirY = -1;
}
void Spaceship::moveDown()
{
animationRow = 2;
dirY = 1;
}
void Spaceship::moveLeft()
{
curFrame = 2;
dirX = -1;
}
void Spaceship::moveRight()
{
curFrame = 1;
dirX = 1;
}
void Spaceship::resetAnim(int pos)
{
if(pos == 1)
{
animationRow = 1;
dirY = 0;
}
else
{
curFrame = 0;
dirX = 0;
}
}
void Spaceship::collide(int objectID)
{
if(objectID == ENEMY)
lives--;
}
17
Решение
Два int
переменные определенный в заголовочном файле. Это означает, что каждый исходный файл, который включает заголовок, будет содержать их определение (включение заголовка является чисто текстовым). Конечно, приводит к множественным ошибкам определения.
У вас есть несколько вариантов, чтобы это исправить.
-
Сделать переменные
static
(static int WIDTH = 1024;
). Они будут по-прежнему существовать в каждом исходном файле, но их определения не будут видны за пределами исходного файла. -
Превратите их определения в декларации, используя
extern
(extern int WIDTH;
) и положить определение в один исходный файл:int WIDTH = 1024;
, -
Вероятно, лучший вариант: сделать переменные
const
(const int WIDTH = 1024;
). Это делает ихstatic
неявно, а также позволяет использовать их в качестве констант времени компиляции, что позволяет компилятору использовать их значение напрямую, а не выдавать код для чтения его из переменной и т. д.
48
Другие решения
Вы не можете помещать определения переменных в файлы заголовков, так как они будут частью всего исходного файла, в который вы включаете заголовок.
#pragma once
просто для защиты от нескольких включений в одном исходном файле, а не от нескольких включений в нескольких исходных файлах.
Вы могли бы объявлять переменные как extern
в заголовочном файле, а затем определять их в одном исходном файле. Или же вы можете объявить переменные как const
в заголовочном файле, и компилятор и компоновщик будут управлять им.
5
const int WIDTH = 1024;
const int HEIGHT = 800;
2
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:
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
- Изменено
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
6,1776 gold badges30 silver badges35 bronze badges
asked Jun 10, 2014 at 9:47
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 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
6,1776 gold badges30 silver badges35 bronze badges
asked Jun 10, 2014 at 9:47
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 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
Visual studio error lnk1169
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Asked by:
Question
fatal error LNK1169: one or more multiply defined symbols found
How can i fix this error?
All replies
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.
Источник
Visual studio error lnk1169
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Asked by:
Question
fatal error LNK1169: one or more multiply defined symbols found
How can i fix this error?
All replies
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.
Источник
Visual studio 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 не должен скрывать переменную от других файлов?
Источник
Visual studio error lnk1169
Write your question here. Hi, it is me again. I am getting this error and cannot figure out what I am doing wrong. It is in visual studios 2013 again BTW.
[#include «stdafx.h» // Precompiled header
#include «iostream» // Input and output stream
using namespace std; // Meaning you don’t have to put std:: before cout Last edited on
can you use code tags please?
for example, you prototype:
int squareIntegers();
but you call it like this:
squareIntegers(22)
you also do not need prototype declarations if you’re implementing them before you call them.
i.e. delete these:
why are you doing calculations and then return zero?
edit:
you also do not need this either:
are wrong, and not even needed.
I did it because I cannot return both answer1 and answer2 twice.
You need to read that link i pasted on functions.
So, I read it but and why are
[int squareIntegers(); // Function Prototype
double squareDouble();
float squareFloat();], wrong. They are function prototypes.
Also, I get an error saying to include «stdafx.h» if I don’t include it.
Also, for squareIntegers(22), I used this in my last program, and it worked fine. I have no idea what else could be the issue.
They are function prototypes.
Yes they are, but they don’t match your functions!
This prototype:
You’re telling the compiler about a different function. This one takes an integer and returns an integer.
This issue becomes apparent when you move your functions implementations below your main function:
(10): error C2660: ‘squareIntegers’ : function does not take 1 arguments
(11): error C2660: ‘squareDouble’ : function does not take 1 arguments
(12): error C2660: ‘squareFloat’ : function does not take 2 arguments
Because your prototypes should be:
Okay, thanks for that, but I still have this error: «fatal error LNK1169: one or more multiply defined symbols found.»
Does this mean in my squareFloat function, I need to make a struct, return the struct name? Will that get rid of this error?
Источник
фатальная ошибка 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 в заголовочном файле, и компилятор и компоновщик будут управлять им.
Источник