Rishats 1 / 1 / 2 Регистрация: 25.08.2013 Сообщений: 55 |
||||||||
1 |
||||||||
13.09.2014, 15:46. Показов 50237. Ответов 6 Метки нет (Все метки)
Добрый день уважаемые.
P.S
0 |
1180 / 893 / 94 Регистрация: 03.08.2011 Сообщений: 2,461 |
|
13.09.2014, 15:49 |
2 |
Что за int.obj? Есть ли в проекте файл int.cpp? Если да, то его нужно удалить или исключить из построения. Нельзя определять функцию больше одного раза ( в данном случае компоновщик говорит, что функция main уже определена в int.obj ).
0 |
1 / 1 / 2 Регистрация: 25.08.2013 Сообщений: 55 |
|
13.09.2014, 16:05 [ТС] |
3 |
Что за int.obj? Есть ли в проекте файл int.cpp? Если да, то его нужно удалить или исключить из построения. Нельзя определять функцию больше одного раза ( в данном случае компоновщик говорит, что функция main уже определена в int.obj ). Вообщем , если создать 1 элемент и произвести компиляцию , ошибок не будет , если создать в проекте еще 1 элемент , прошу заметить с любым названием , проблема вновь приходит , прилажу скрин. Добавлено через 16 секунд Добавлено через 26 секунд
0 |
1180 / 893 / 94 Регистрация: 03.08.2011 Сообщений: 2,461 |
|
13.09.2014, 16:09 |
4 |
РешениеВ проекте не должно быть 2 функции main, это Вам и говорит компоновщик. Нельзя в проекте определять функцию с одним и тем же именем в разных файлах.
2 |
1 / 1 / 2 Регистрация: 25.08.2013 Сообщений: 55 |
|
13.09.2014, 16:12 [ТС] |
5 |
Вот я чайник , спасибо , все ясно! Добавлено через 3 минуты
В проекте не должно быть 2 функции main Спасибо )
0 |
1 / 1 / 0 Регистрация: 04.04.2015 Сообщений: 5 |
|
04.04.2015, 15:30 |
6 |
ну я сделал вот так #include <iostream> int main2() cout << «Введите произвольное число: «;
1 |
0 / 0 / 0 Регистрация: 09.02.2022 Сообщений: 1 |
|
09.02.2022, 17:35 |
7 |
Спасибо
0 |
Решил проверить код из книги ООП в С++ Лафоре но в Visual Studio не получается его повторить
#include "stdafx.h"
#include <iostream>
#include <conio.h>
using namespace std;
int Main()
{
for (int j = 0; j<80; j++)
{
char ch = (j%8) ? ' ' : 'x';
cout << ch;
}
return 0;
}
Подскажите пожалуйста, что я делаю не так?
В Borland все работает
задан 4 мая 2018 в 18:14
3
Причина: функция int main()
должна быть с маленькой буквы
Почему в данном файле он VS выдавал ошибку, если писать её с маленькой? Потому что точкой входа в программу в данном случае в VS является файл *.cpp
, имя которого совпадает с именем проекта, то есть ConsoleApplication1.cpp
. Именно там находится int main()
, и оно уже было сгенерированно самой IDE, но вы видимо не увидели.
Таким образом, весь код надо поместить в ConsoleApplication1.cpp
.
ответ дан 4 мая 2018 в 18:45
DanDan
557 бронзовых знаков
Разобрался сам. причин не знаю но в новом проекте все заработло
ответ дан 4 мая 2018 в 18:28
FaTaLFaTaL
91 бронзовый знак
2
Я не знаю, откуда Вы брали тексты примеров, но если взять их с ОФЦИАЛЬНОГО сайта (в книжке есть ссылка) и скачать, то выглядит этот текст так:
// condi.cpp // prints 'x' every 8 columns
// demonstrates conditional operator
#include <iostream> using namespace std;
int main() { for(int j=0; j<80; j++)
//for every column,
{ //ch is 'x' if column is
char ch = (j%8) ? ' ' : 'x'; //multiple of 8, and
cout << ch; //' ' (space) otherwise
} return 0; }
И всё великолепно компиллируется и работает.
ответ дан 8 мая 2018 в 4:45
SergeySergey
13.2k1 золотой знак12 серебряных знаков27 бронзовых знаков
Background
I have a project named PersonLibrary which has two files.
- Person.h
- Person.cpp
This library produces a static library file. Another project is TestProject which uses the PersonLibrary (Added though project dependencies in VS008). Everything worked fine until I added a non-member function to Person.h. Person.h looks like
class Person
{
public:
void SetName(const std::string name);
private:
std::string personName_;
};
void SetPersonName(Person& person,const std::string name)
{
person.SetName(name);
}
Person.cpp defines SetName function. When I try to use SetPersonName from TestProject, I get error LNK2005: already defined. Here is how I used it
#include "../PersonLibrary/Person.h"
int main(int argc, char* argv[])
{
Person person;
SetPersonName(person, "Bill");
return 0;
}
Workarounds tried
1 — I have removed the Person.cpp and defined the whole class in Person.h. Error gone and everything worked.
2 — Changed the SetPersonName modifier to static. Like the below
static void SetPersonName(Person& person,const std::string name)
{
person.SetName(name);
}
Questions
- Why the code shown first is not working as I expected?
- What difference static made here?
- What is the approapriate solution for this problem?
Thanks
asked Mar 7, 2009 at 18:05
Navaneeth K NNavaneeth K N
15.3k37 gold badges126 silver badges184 bronze badges
You either have to
- move
SetPersonName
‘s definition to a .cpp file, compile and link to the resulting target - make
SetPersonName
inline
This is a well known case of One Definition Rule violation.
The static keyword makes the function’s linkage internal i.e. only available to the translation unit it is included in. This however is hiding the real problem. I’d suggest move the definition of the function to its own implementation file but keep the declaration in the header.
answered Mar 7, 2009 at 18:11
dirkgentlydirkgently
107k16 gold badges131 silver badges187 bronze badges
4
When you compile you’re library, its lib file contains a definition for SetPersonName. When you compile your program that uses the library, since it includes the header, and you’ve written the code inline in the header it also compiles in a definition for SetPersonName. Two definitions for the same function aren’t (generally) allowed. The static keyword tells the compiler that the function shouldn’t be exposed outside of the current translation unit (discrete piece of code you are compiling), so the definition in the library isn’t visible to the linker.
The appropriate solution to this problem depends on your goals. Header files with static function declarations is almost never what you want. From a design standpoint I would recommend getting rid of SetPersonName altogether, and just use Person::SetName.
However, failing that, I would implement it much like you’ve done for the rest of your functionality, declarations in the header, and implementation in the .cpp. Inline functions associated with a library will tend to diminish many of the advantages of using a library in the first place.
answered Mar 7, 2009 at 18:22
Logan CapaldoLogan Capaldo
39.4k5 gold badges63 silver badges78 bronze badges
By declaring the function static you are scoping it to the current translation unit, so in effect you have added a new SetPersonName function in your main file, and would be calling that not the one defined in the library.
The correct solution is to declare SetPersonName as extern in person.h and implement it in person.cpp
Person.h
extern void SetPersonName(Person& person,const std::string name);
Person.cpp
void SetPersonName(Person& person,const std::string name)
{
person.SetName(name);
}
answered Mar 7, 2009 at 18:12
Rob WalkerRob Walker
46.4k15 gold badges98 silver badges136 bronze badges
-
The function SetPersonName will be compiled into each objectfile that includes the Person.h file, thus making the linker seeing several functions and giving the error.
-
By writing static you state that the function will only be visible within a single objectfile. You will still get several functions in you binary but now you will not get the errors.
-
Try to write
inline
before the function likeinline void SetPersonName(Person& person,const std::string name) { person.SetName(name); }
…because the function is pretty simple it is OK I think to have it as an inline. An inline will place the necessary code where the function is used, without actually creating a function to be called.
answered Mar 7, 2009 at 18:09
A solution would be to make that function a static method. That will stop the «already defined» errors.
answered Mar 7, 2009 at 18:18
GeoGeo
92.8k117 gold badges342 silver badges519 bronze badges
I had a similar situation as described clearly by @logan-capaldo above.
A CPP source file (myfile.cpp) contained a function MyFunction. When building, this got compiled into myfile.obj. But the main CPP file (main.cpp) also included myfile.cpp, so the function MyFunction was being included/compiled/linked twice, leading to the «LNK2005 already defined» error.
This is messy but I didn’t have time to fix it properly. The quickest fix (in VS Express 2012) was to right-click myfile.cpp in Solution Explorer, go to Properties and change Excluded From Build to Yes. I guess this prevents one of the OBJ files from being created and/or linked and so removes the error.
answered Jan 27, 2016 at 16:22
PaulPaul
6698 silver badges9 bronze badges
For anyone landing here dealing with this error in a Qt project, make sure you don’t have any non-signal functions defined under signals:
in your header files.
Incorrect, throws LNK2005
on Foo::promiseData()
:
class Foo : public QObject {
Q_OBJECT
public:
explicit Foo(QObject* parent = nullptr);
signals:
void dataReady(QList<QObject*> data) const;
void promiseData() const; // <-- This function is not supposed to be a signal.
Correct:
class Foo : public QObject {
Q_OBJECT
public:
explicit Foo(QObject* parent = nullptr);
void promiseData() const;
signals:
void dataReady(QList<QObject*> data) const;
answered Sep 13, 2019 at 21:18
#include <iostream>
using namespace std;
int main()
{
cout << "Hello world!";
}
Ошибка LNK2005 main уже определен в ConsoleApplication1.obj ConsoleApplication1 C:UsersолехDesktopcccConsoleApplication1ConsoleApplication1my.obj 1
Ошибка LNK1169 обнаружен многократно определенный символ — один или более ConsoleApplication1 C:UsersолехDesktopcccConsoleApplication1x64DebugConsoleApplication1.exe 1
Я совсем ламер не знаю как быть. Помогите кто чем сможет
-
Вопрос задан05 янв.
-
121 просмотр
Пригласить эксперта
Вы работаете в VS IDE и у вас, видимо, в другом файле в вашем проекте уже определена функция main.
Самый простой выход — создайте пустой проект (а не консольный) и напишите ваш код
-
Показать ещё
Загружается…
13 июн. 2023, в 15:58
400 руб./за проект
13 июн. 2023, в 15:58
400 руб./за проект
13 июн. 2023, в 15:58
400 руб./за проект
Минуточку внимания
- Remove From My Forums
-
Question
-
I recently installed VC++ 2005 EXP edition.
1) I created a project name Radius and created two new items hello.cpp and area.cpp.
2) area.cpp is the first item and hello.cpp is the second one.
3) When I build the project Radius, I got the error
LNK2005: _main already defined in area.obj
Can you guide me to fix the compilation error.
Thanks GKW82
Answers
-
This error is because of multiple definitions of main. You must have defined main in area.cpp as well as in hello.cpp. In C/C++ programs, you can write only one main per application.
Remove one definition of main and it should work fine.
Cheers