Int main void ошибка

Hello programming world.

I am currently doing my first programming course at university and our instructor said the function

int main (); //without the curly braces// is valid. 

I may have misheard him/misinterpreted him, as when I try and run a console with that, it gives an error. But when I do int main() {}; it runs fine.
So:
1. Are the curly braces needed regardless of the content in the body?

  1. How did the function run without the return 0.

  2. Using this, what is the shortest possible int main / void main function possible?

as requested, here is the error:

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Thank you so much :)

Xara's user avatar

Xara

8,62816 gold badges52 silver badges82 bronze badges

asked Feb 14, 2014 at 20:17

user3311681's user avatar

2

In C++, there are two correct definitions for main:

int main() {
    // ...
}

and

 int main(int argc, char *argv[]) {
     // ...
 }

or equivalent. (Other implementation-defined forms are possible, but we can ignore those. And the return type is always int, at least for hosted implementations; void main() is wrong.)

The braces { and } are part of the syntax of a function definition; they’re not optional.

You can provide a declaration for main, such as

int main();

but there’s no real point in doing so. That’s a declaration, not a definition — and you still need to have a definition somewhere.

A return 0; at the end is not required. This is a special case that applies only to main, not to other functions: if execution reaches the closing }, it does an implicit return 0;.

The shortest legal program would probably be:

int main(){}

answered Feb 14, 2014 at 20:22

Keith Thompson's user avatar

Keith ThompsonKeith Thompson

254k44 gold badges424 silver badges628 bronze badges

Thats the difference between a function definition and declaration (see What is the difference between a definition and a declaration?

Basically int main(); is a prototype telling the compiler that you will have a function called main, which returns an int, but you do not implement it yet.

the int main() {} is the implementation of the function, thus the curly braces, giving it a function body and full implementation.

Community's user avatar

answered Feb 14, 2014 at 20:24

MatthiasB's user avatar

MatthiasBMatthiasB

1,7598 silver badges18 bronze badges

1

I’d like to clarify a few things.

int main();

is a function declaration, i.e. it lets other functions / classes know about it.
However, it does not define main, meaning it says nothing about what main actually does.
Since every C++ program must define main, as it is run first, your compiler will definitely give a compile error.

By writing

int main() {}

You are defining main by specifying that main does nothing, so it will run.

Finally, C++ compilers will implicitly add a return 0; statement if you do not return anything, as it is an indicator to the operating system that the program ran successfully.

For more information, see https://stackoverflow.com/a/204483/2512775 on what main should return.

Community's user avatar

answered Feb 14, 2014 at 20:29

James Zhu's user avatar

James ZhuJames Zhu

1401 silver badge6 bronze badges

Your error code means that you have not declared the main() function properly. What you should do is add the curly braces to signify the block of code that your application will run in.

Although the compiler will add a return statement if it isn’t given one, just add one to make sure.

answered Feb 14, 2014 at 20:35

Adil Patel's user avatar

Adil PatelAdil Patel

1711 silver badge11 bronze badges

Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «int main(void)» уже имеет текст реализации (C2084)

Source.cpp

#include <iostream>
#include <Windows.h>
#include "func.h"

using namespace std;

void Interface();

int main() {
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    Interface();
}

func.h

#pragma once
#include "Source.cpp"

void Interface() {
    int quest;
    while (true) {
        cout << "1. Открыть базу" << endl;
        cout << "2. Закрыть программу" << endl;
        cout << "Номер пути _b";
        cin >> quest;
        if (quest = 1) {
            cout << "Открыто!";
        }
        else if (quest = 2) {
            cout << "Закрыто!";
        }
    }
}

задан 1 янв 2018 в 19:25

kbx's user avatar

1

У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp.

В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h — это

void Interface();

Все остальное — в .cpp-файлах, и не включать .cpp-файлы с помощью директивы #include — иначе вы получаете нарушение правила одного определения.

ответ дан 1 янв 2018 в 19:50

Harry's user avatar

HarryHarry

215k15 золотых знаков117 серебряных знаков228 бронзовых знаков

4

2 / 2 / 0

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

Сообщений: 28

1

программа выдает ошибку, как ее поправить

09.02.2014, 22:38. Показов 1976. Ответов 13


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

Добрый вечер! программа выдает ошибку: функция «int main(void)» уже имеет текст реализации
есть ли способ ее исправить??



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

09.02.2014, 22:38

Ответы с готовыми решениями:

Программа которая выдает платформу компьютера выдает ошибку
unit Unit1;

interface

uses
Windows, Messages, SysUtils, Variants, Classes, Graphics,…

При решении программа выдаёт значение функции, равное 0 или выдаёт ошибку. Что не так?
#include &lt;iostream&gt;
#include &lt;iomanip&gt;
#include &lt;cmath&gt;
using namespace std;

long Fact(short…

Почему программа при работе выдает ошибку ‘INVALID POINTER OPERATION’ и работает потом как надо?
Суть в следующем: программа генерирует задания, создает через Create панель на нее помещает…

У меня не выдает ошибку, но программа действует не так как я хочу. Глаза должны двигаться за мышкой,но этого не происход
procedure TForm1.BQuitClick(Sender: TObject);
begin
close
end;

procedure…

13

22 / 22 / 7

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

Сообщений: 93

09.02.2014, 22:39

2

strannik11, какой компилятор используйте? Покажите код



0



strannik11

2 / 2 / 0

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

Сообщений: 28

09.02.2014, 22:41

 [ТС]

3

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
     setlocale(0,"");
 
   FILE * f;
   char bukv [1000];
   char buk[400] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNMйцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
   char pre[4] = "!?.";
   char s;
    s=0;
    char ch;
   f = fopen ("Input_1.txt" , "r");
   if (f == NULL) perror ("Error opening file");
   else {
     if ( fgets (bukv , 1000 , f) != NULL )
       puts (bukv);
      while (!feof(f))
    {
    ch = fgetc(f);
    if(ch == ' ' || ch == 'n' || ch == 't') s++; 
    } 
    fseek(f,0,SEEK_SET); 
    printf("Слов в тексте : %i",s+1); 
    std::stringstream ss;
int i = s+1;
ss << s+1;
std::string stroc = ss.str();
  printf("%s",stroc.c_str());
    
     fclose (f);
   }
}
 
int main()
{
    FILE * f1;
    string stroc;
    f1 = fopen ("Input_1.txt" , "wb");
   if (f1 == NULL) perror ("Error opening file");
    {
  
        fputs(stroc.c_str(),f1);
    }
    fclose(f1);
    }



0



17452 / 9279 / 2269

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

Сообщений: 16,244

09.02.2014, 22:43

4

Так у вас реально два main`а Уберите лишний и проблема решена.



1



strannik11

2 / 2 / 0

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

Сообщений: 28

09.02.2014, 22:55

 [ТС]

5

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
     setlocale(0,"");
 
   FILE * f;
   char bukv [1000];
   char buk[400] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNMйцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
   char pre[4] = "!?.";
   char s;
    s=0;
    char ch;
   f = fopen ("Input_1.txt" , "r");
   if (f == NULL) perror ("Error opening file");
   else {
     if ( fgets (bukv , 1000 , f) != NULL )
       puts (bukv);
      while (!feof(f))
    {
    ch = fgetc(f);
    if(ch == ' ' || ch == 'n' || ch == 't') s++; 
    } 
    fseek(f,0,SEEK_SET); 
    printf("Слов в тексте : %i",s+1); 
    std::stringstream ss;
int i = s+1;
ss << s+1;
std::string stroc = ss.str();
  printf("%s",stroc.c_str());
    
     fclose (f);
   }
 
 
 
 
    FILE * f1;
    string stroc;
    f1 = fopen ("Input_1.txt" , "wb");
   if (f1 == NULL) perror ("Error opening file");
    {
  
        fputs(stroc.c_str(),f1);
    }
    fclose(f1);
    }

поправил, появился новый вопрос, почему у меня из исходного текстовика улетел весь текст? и во второй не прошло не одной записи?

Добавлено через 8 минут
почему из первого файла все улетело понял, была ошибка в строке:

C++
1
f1 = fopen ("Input_1.txt" , "wb");

заменил имя файла, но во второй должна записаться строка:

C++
1
{fputs(stroc.c_str(),f1);

подскажите почему ничего не происходит?



0



DrOffset

17452 / 9279 / 2269

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

Сообщений: 16,244

09.02.2014, 23:40

6

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

подскажите почему ничего не происходит?

У вас std::string stroc первый раз объявлена внутри условия else, по правилам С++ ее время жизни ограничено блоком. Ниже вы создали еще одну (другую!) переменную stroc, она естественно пуста. Поправить можно перенеся объявление выше:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
std::string stroc; //тут
 
if(f == NULL) //первое условие
{
    //.... ошибка
}
else
{
   // здесь читаем в строку
}
 
//.....
 
if(f1 == NULL) // второе условие
{
    //.... ошибка
}
else
{
    fputs(stroc.c_str(), f1);
}



1



strannik11

2 / 2 / 0

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

Сообщений: 28

10.02.2014, 13:37

 [ТС]

7

поправил так как вы посоветовали, но запись почему то так и не происходит, не могу понять почему?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
#include "stdafx.h"
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
     setlocale(0,"");
   std::string stroc;
   FILE * f;
   char bukv [1000];
   char buk[400] = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNMйцукенгшщзхъфывапролджэячсмитьбюЙЦУКЕНГШЩЗХЪФЫВАПРОЛДЖЭЯЧСМИТЬБЮ";
   char pre[4] = "!?.";
   char s;
    s=0;
    char ch;
    
   f = fopen ("Input_1.txt" , "r");
   if (f == NULL) perror ("Error opening file");
   else {
     if ( fgets (bukv , 1000 , f) != NULL )
       puts (bukv);
      while (!feof(f))
    {
    ch = fgetc(f);
    if(ch == ' ' || ch == 'n' || ch == 't' || ch == 'n, ') s++; 
    } 
    fseek(f,0,SEEK_SET); 
    printf("Слов в тексте : %i  ",s); 
    std::stringstream ss;
int i = s;
ss << s;
std::string stroc = ss.str();
 
     fclose (f);
   }
   {
    FILE * f1;
    
    f1 = fopen ("Output_1.txt" , "wb");
    
        fputs(stroc.c_str(),f1);
    
    
    fclose(f1);
    system ("pause");
    }
    
}



0



DrOffset

17452 / 9279 / 2269

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

Сообщений: 16,244

10.02.2014, 15:11

8

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

поправил так как вы посоветовали, но запись почему то так и не происходит, не могу понять почему?

Ошибка та же. Объявление должно быть одно, а у вас их опять два.

C++
1
std::string stroc = ss.str();

заменить на

C++
1
stroc = ss.str();



1



2 / 2 / 0

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

Сообщений: 28

10.02.2014, 15:26

 [ТС]

9

DrOffset, спасибо вам большое за советы, но эту ошибку исправил уже сам)) очень помогли мне.

Добавлено через 4 минуты
можно последний вопрос задать? как мне сделать так что бы моя программа не прибавляла в счетчике повторные слова, что бы например, слово «привет» считалось 1 раз, а потом программа пропускала бы его и шла дальше.



0



DrOffset

17452 / 9279 / 2269

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

Сообщений: 16,244

10.02.2014, 19:47

10

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

как мне сделать так что бы моя программа не прибавляла в счетчике повторные слова, что бы например, слово «привет» считалось 1 раз, а потом программа пропускала бы его и шла дальше.

Мне кажется самый просто способ для вас это использовать std::set. Добавлять туда слова из файла, дубликаты отсеятся.
Если я правильно понял задачу, то как-то так.

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
#include <string>
#include <cstdio>
#include <set>
#include <clocale>
#include <cstdlib>
 
int main()
{
    setlocale(0, "");
    std::set<std::string> words;
 
    if(FILE *f1 = fopen("Input_1.txt", "r"))
    {
        char buf[100];
        int  len = 0;
        char end = 0;
        while(fscanf(f1, "%99s%n%c", buf, &len, &end) > 0)
        {
            printf("%s ", buf);
            words.insert(std::string(buf, len));
        }
        printf("n");
        fclose(f1);
 
        printf("Words count: [%i]n", words.size());
    }
    else
    {
        perror("Error opening file 'Input_1.txt'");
        return 1;
    }
 
 
    if(FILE *f2 = fopen("Output_1.txt", "w"))
    {
        fprintf(f2, "%d", words.size());
        fclose(f2);
    }
    else
    {
        perror("Error opening file 'Output_1.txt'");
        return 1;
    }
    system("pause");
    return 0;
}



0



2 / 2 / 0

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

Сообщений: 68

10.02.2014, 21:30

11

что ты мучаешься ? просто используй void main() и не мучайся))



0



17452 / 9279 / 2269

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

Сообщений: 16,244

10.02.2014, 21:45

12

Цитата
Сообщение от РАСУЛл
Посмотреть сообщение

что ты мучаешься ? просто используй void main() и не мучайся))

Такая форма main запрещена в С++.

3.6.1/2

An implementation shall not predefine the main function. This function shall not be overloaded. It shall
have a return type of type int
, but otherwise its type is implementation-defined. All implementations shall
allow both of the following definitions of main:
int main() { /* … */ }
and
int main(int argc, char* argv[]) { /* … */ }



0



2 / 2 / 0

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

Сообщений: 68

10.02.2014, 21:49

13

ошибаешься , она часто используется ….



0



17452 / 9279 / 2269

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

Сообщений: 16,244

11.02.2014, 00:27

14

Цитата
Сообщение от РАСУЛл
Посмотреть сообщение

ошибаешься , она часто используется ….

Любой современный компилятор по-умолчанию выдаст ошибку. Кроме VS, которая это пропустит (расширение компилятора), но это исключительно ее личное дело. Программист, пишущий портабельный код, не должен на это закладываться. А тот, который не пишет, все равно должен про это знать.



0



Привет. Есть программа по типу консольного пеинта: решетка- курсор, управляется на wasd, прописана прорисовка в void DrawPoint(), а управление — в void logic(). Так же присутствует возможность оставлять за собой нолики на небольшом расстоянии от курсора, реализовано в void DrawPaint(). все завернуто в мейне в бесконечный цикл. При компиляции не работает ничего. Что не так?

#include <iostream>
#include <conio.h>
#include<cstdlib>

using namespace std;
int x = 12;
int y = 12;
int dir = 0;
void DrawPoint()
{
if (dir == 0)
{
for (int i = 0; i <= x; i++)
{
cout<< " ";
for (int j = 0; j <= y; j++)
{
cout << endl;
if (i == x && j == y)
{
cout<< "#";
}
}
}
}
if (dir == 1)
{
for (int i = 0; i < x; i++)
{
if (i == x)
{
cout<< "#";
x++;
}
else
{
cout<< " ";
x++;
}
}
}
if (dir == 2)
{
for (int i = 0; i < x; i++)
{
if (i == x)
{
cout<< "#";
x = x - 1;
}
else
{
cout<< " ";
}
}
}
if (dir == 3)
{
for (int i = 0; i < x; i++)
{
cout<< " ";
for (int j = 0; j < y; j++)
{
if (i == x && j == y)
{
cout<< "#";
y++;
}
else
{
cout<< endl;
y++;
}
}
}

if (dir == 4)
{
for (int i = 0; i <= x; i++)
{
cout<< " ";
for (int j = 0; j <= y; j++)
{
if (i == x && j == y)
{
cout<< "#";
y = y - 1;
}
else
{
cout<< endl;
y = y - 1;
}
}
}
}
}
}
void logic()
{
switch (_getch())
{
case 'w':
dir = 3;
break;

case 's':
dir = 4;
break;

case 'a':
dir = 2;
break;

case 'd':
dir = 1;
break;

default:
dir = 0;
break;
}
}

void DrawPixel()
{
int a[200];
int b[200];
if (kbhit())
{
for (int z = 1; z <= 200; z++)
{
a[z] = x;
for (int l = 1; l <= 200; l++)
{
b[l] = y;

switch (_getch())
{
case 'o':
for (int u = 0; u < a[z]; u++)
{
cout<< " ";
for (int o = 0; o < b[l]; o++)
{
if (u == a[z] - 1 && o == b[l] - 1)
{
cout<< "O";
}
}
}
}
}
}
}
system ("cls");
}

int main()
{
for (int i = 0; i < 1;)
{
void logic();
void DrawPoint();
void DrawPixel();
}
return 0;
}

Перейти к контенту

Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «int main(void)» уже имеет текст реализации (C2084)

Source.cpp

#include <iostream>
#include <Windows.h>
#include "func.h"

using namespace std;

void Interface();

int main() {
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    Interface();
}

func.h

#pragma once
#include "Source.cpp"

void Interface() {
    int quest;
    while (true) {
        cout << "1. Открыть базу" << endl;
        cout << "2. Закрыть программу" << endl;
        cout << "Номер пути _b";
        cin >> quest;
        if (quest = 1) {
            cout << "Открыто!";
        }
        else if (quest = 2) {
            cout << "Закрыто!";
        }
    }
}

задан 1 янв 2018 в 19:25

kbx's user avatar

1

У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp.

В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h — это

void Interface();

Все остальное — в .cpp-файлах, и не включать .cpp-файлы с помощью директивы #include — иначе вы получаете нарушение правила одного определения.

ответ дан 1 янв 2018 в 19:50

Harry's user avatar

HarryHarry

210k15 золотых знаков115 серебряных знаков224 бронзовых знака

4

Dmitriy1342

1 / 1 / 0

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

Сообщений: 37

1

Ошибка: Функция уже имеет текст реализации.

13.02.2012, 14:54. Показов 20250. Ответов 7

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


Вылезает данная ошибка error C2084: функция «double hypot(double,double)» уже имеет текст реализации. Это мой вариант программы, пробовал скопировать текст c учебника — не помогло. Что делать?

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <cmath>
#include <locale>
#include <conio.h>
 
using namespace std;
double hypot (double a, double b); 
 
int main()
{
    setlocale (LC_ALL, "Russian");
 
    double a, b;
 
    cout <<"Введите значение первого катета: ";
    cin >>a;
    cout <<"Введите значение второго катета: ";
    cin >>b;
    cout <<"При катетах "<<a<<" и "<<b<<" гипотенуза равна "<<hypot (a, b);
    getch();
    return 0;
}
 
double hypot (double a, double b)
{
    return sqrt ((a*a)+(b*b));
}
 Комментарий модератора 
Используйте теги форматирования кода!

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

1

Эксперт С++

5053 / 3114 / 271

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

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

13.02.2012, 15:00

2

Dmitriy1342, переименуйте функцию.

1

return (true);

1976 / 1111 / 221

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

Сообщений: 2,345

13.02.2012, 15:02

3

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

уже имеет текст реализации

Русским по белому написано, функция с таким именем и насколько помнится с таким же содержанием уже описана в math.h
Назовите свою функцию по другому или воспользуйтесь стандартной

2

-=ЮрА=-

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

Автор FAQ

13.02.2012, 17:13

4

Dmitriy1342, а можете не менять название а просто записать функцию в вашем собственном namespace ИМХО все так любят ставить std:: почему бы не воспользоваться рефакторингом в свою пользу!

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cmath>
using namespace std;
 
namespace my
{
    double hypot (double a, double b)
    {
            return sqrt ((a*a)+(b*b));
    } 
};
 
int main()
{
    //setlocale (LC_ALL, "Russian");
    system("chcp 1251");
    double a, b;
    cout <<"Введите значение первого катета: ";
    cin >>a;
    cout <<"Введите значение второго катета: ";
    cin >>b;
    cout<<"При катетах "<<a<<" и "<<b
        <<" гипотенуза равна "
        <<my::hypot (a, b)//Вот использование рефакторинга во всей красе
        <<endl;
    system("pause");
    return 0;
}

PS:Раз уж мы хотим стать «продвинутыми дядьками», то почему бы по продвинутому не действовать?

Миниатюры

Ошибка: Функция уже имеет текст реализации.
 

0

Dmitriy1342

1 / 1 / 0

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

Сообщений: 37

13.02.2012, 17:35

 [ТС]

5

Цитата
Сообщение от -=ЮрА=-
Посмотреть сообщение

Dmitriy1342, а можете не менять название а просто записать функцию в вашем собственном namespace ИМХО все так любят ставить std:: почему бы не воспользоваться рефакторингом в свою пользу!

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#include <iostream>
#include <cmath>
using namespace std;
 
namespace my
{
    double hypot (double a, double b)
    {
            return sqrt ((a*a)+(b*b));
    } 
};
 
int main()
{
    //setlocale (LC_ALL, "Russian");
    system("chcp 1251");
    double a, b;
    cout <<"Введите значение первого катета: ";
    cin >>a;
    cout <<"Введите значение второго катета: ";
    cin >>b;
    cout<<"При катетах "<<a<<" и "<<b
        <<" гипотенуза равна "
        <<my::hypot (a, b)//Вот использование рефакторинга во всей красе
        <<endl;
    system("pause");
    return 0;
}

PS:Раз уж мы хотим стать «продвинутыми дядьками», то почему бы по продвинутому не действовать?

Хм, а что такое system(«chcp 1251»); ?

0

IFree Host

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

13.02.2012, 17:39

6

chcp — изменение кодовой страницы cmd.exe

Очень часто нужно, чтобы вместо кодовой страницы cp866 (заданной по-умолчанию) данные были в cp1251 (команда chcp 1251) или в utf8 (chcp 65001).

0

-=ЮрА=-

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

Автор FAQ

13.02.2012, 17:41

7

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

Хм, а что такое system(«chcp 1251»); ?

— да єто руссификация на старых компиляторах, вместо неё поставь + в хедеры #include <locale>

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

setlocale (LC_ALL, «Russian»);

видишь же я закоментил её…

1

1 / 1 / 0

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

Сообщений: 37

13.02.2012, 17:42

 [ТС]

8

А, понятно, спасибо.

0

Может кто-нибудь помочь мне разобраться с этой ошибкой

У меня есть два файла под исходными файлами в Visual Studio 2013 Express
main.cpp и Variables.cpp

ниже приведены коды

ОШИБКА СКРИНШОТА
ПРЕДУПРЕЖДЕНИЕ И ОШИБКА СКРИНШОТА

main.cpp

#include <iostream>
#include "Variables.cpp"using namespace std;

int main()
{
int a = 3;

cout << "Hello World" << endl;
cout << "The value of a: " << a << endl;
getchar();

return 0;

}

Variables.cpp

#include <iostream>
#include <string>

using namespace std;

int main()
{
//Declaring Variables
int a = 3;
float b = 33.3;
double c = 223.334;
char d = 'i';
string e = "This is a test text !";

//Printing
cout << "The value of a: " << a << endl;
cout << "The value of b: " << b << endl;
cout << "The value of c: " << c << endl;
cout << "The value of d: " << d << endl;
cout << "The value of e: " << e << endl;

//Show Msg
getchar();
return 0;

}

ошибка

Предупреждение 1
предупреждение C4305: «инициализация»: усечение с «double» до «float» c: users iifra Documents visual studio 2013 projects testproject001 testproject001 variables.cpp 11 1 TestProject001

Ошибка 2
ошибка C2084: функция ‘int main (void)’ уже имеет тело c: users iifra Documents visual studio 2013 projects testproject001 testproject001 main.cpp 6 1 TestProject001

Предупреждение 3
предупреждение C4305: «инициализация»: усечение с «double» до «float» c: users iifra Documents visual studio 2013 projects testproject001 testproject001 variables.cpp 11 1 TestProject001

-3

Решение

Изменить название функции main() присутствует в Variables.cpp для любого другого имени.
Вы не можете использовать две функции main () в одном проекте, потому что ваша ОС находит основную функцию, присутствующую в вашем проекте, когда вы запускаете проект. И здесь ОС путает, какую основную функцию вызывать первой.

1

Другие решения

Это вопрос для начинающих. Два аспекта:

  • Вы можете иметь только 1 функцию «main», так как «main» является особенной (точка входа)
  • вы можете использовать несколько исходных файлов; используйте заголовок для объявлений и источник для определений

например.:

основной источник:

// main.cpp
#include <iostream>
#include "variables.hpp"
int main()
{
int a = 3;

std::cout << "Hello World" << std::endl;
std::cout << "The value of a: " << a << std::endl;

//invoke f
f();

//getchar();

return 0;
}

Заголовок переменных:

//variables.hpp

void f();

источник переменных:

//variables.cpp
#include <iostream>
#include "variables.hpp"
void f()
{
std::cout << "Bla" << std::endl;
}

Компилятор будет обрабатывать их как два модуля перевода и создает два файла obj (то есть main.obj и variables.obj), а компоновщик объединит их вместе как один exe.

Вы используете Visual Studio. Поместите заголовочные файлы в папку заголовка, а файлы cpp — в исходную папку.

0

Перейти к контенту

Делаю одну программу для эксперимента и возникла одна ошибка.
Сделал новый проект и оставил ту же функцию и те же свойства, а ошибка так и осталась, в чем может быть дело?
Ошибка: функция «int main(void)» уже имеет текст реализации (C2084)

Source.cpp

#include <iostream>
#include <Windows.h>
#include "func.h"

using namespace std;

void Interface();

int main() {
    SetConsoleCP(1251);
    SetConsoleOutputCP(1251);
    Interface();
}

func.h

#pragma once
#include "Source.cpp"

void Interface() {
    int quest;
    while (true) {
        cout << "1. Открыть базу" << endl;
        cout << "2. Закрыть программу" << endl;
        cout << "Номер пути _b";
        cin >> quest;
        if (quest = 1) {
            cout << "Открыто!";
        }
        else if (quest = 2) {
            cout << "Закрыто!";
        }
    }
}

задан 1 янв 2018 в 19:25

kbx's user avatar

1

У вас неверное понимание, что должно находиться в заголовочном файле, а что — в .cpp.

В заголовочном файле располагайте объявления, а определения — в cpp-файле. В заголовочном файле располагаются также inline-реализации, шаблоны и т.п. вещи, но в вашем случае все, что следует разместить в func.h — это

void Interface();

Все остальное — в .cpp-файлах, и не включать .cpp-файлы с помощью директивы #include — иначе вы получаете нарушение правила одного определения.

ответ дан 1 янв 2018 в 19:50

Harry's user avatar

HarryHarry

210k15 золотых знаков114 серебряных знаков224 бронзовых знака

4

  • Remove From My Forums
  • Question

  • Hi All,

    I’m migrating an existing project from vs 6.0 to vs 2008. I get the below error,

    »  error C2084: function ‘tstring::tstring(void)’ already has a body «

    Error Code in tstring.cpp file:

    tstring::tstring()
    {
    }

    As the error message suggest there is another constructor for the same function in the header file tstring.h:

    // Constructors
    inline tstring::tstring() : base_class()
    {
    }

    I don’t understand why «tstring::tstring()» constructor is there twice in cpp and h file and how to fix this error. Shall I remove tstring::tstring(){} completely?, that way a duplicate entry is removed.. Any help to fix this issue is
    greatly appreciated. Thanks in advance!

    P.S: This error does not occur when compiled in vs 6.0

    Regards,

    Ankush

Answers

  • On 19/02/2014 12:29, ankushkumar wrote:

    »  error C2084: function ‘tstring::tstring(void)’ already has a body/
    Error Code in tstring.cpp file:

    tstring::tstring()
    {
    }

    As the error message suggest there is another constructor for the same function in the header file tstring.h:

    // Constructors
    inline tstring::tstring() : base_class()
    {
    }

    I don’t understand why «tstring::tstring()» constructor is there twice in cpp and h file and how to fix this error. Shall I remove tstring::tstring(){} completely?, that way a duplicate entry is removed..

    You may want to remove one of the two. Considering that the body is just empty, it seems a good candidate to be inlined, so I’d just use this in the header file:

    inline tstring::tstring()
    {
    }
    

    I’m not sure about the base_class() initialization… should it be just automatic?

    P.S: This error does not occur when compiled in vs 6.0

    Note that the C++ compiler that ships with VS2008 is better than the one in VC6 (VS2008’s C++ compiler conforms to the C++98/03 standard, VC6 compiler doesn’t).
    So, it’s very possible that the C++ compiler that comes with VS2008 emits several errors that the VC6 compiler ignored.

    Giovanni

    • Marked as answer by

      Tuesday, February 25, 2014 8:34 AM

I receive the following error:

1> resistor.cpp(7): error C2084: function 'Resistor::Resistor(int,std::string,double,int [])' already has a body
1>          resistor.h(25) : see previous definition of '{ctor}'

With every single one of my class functions, even though in resistor.h I have don’t have any empty implementations:

Resistor.h:

class Resistor
{
private:
   int rIndex;
   double resistance; // resistance (in Ohms)
   string name; // C++ string holding the label
   int endpointNodeIDs[2]; // IDs of nodes it attaches to

public:    
   Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2]);

}

Resistor.cpp:

Resistor::Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2])
{
    if (nodeArray[endpoints_[0]].addResistor(rIndex_) && NodeArray[endpoints_[1]].addResistor(rIndex_))
{
    rIndex = rIndex_;
    name = name_;
    resistance = resistance_;
    endpointNodeIDs[0] = endpoints_[0];
    endpointNodeIDs[1] = endpoints_[1];
}

return;
}

etc. for each of my class functions

Can anybody help me?

p.s. I also receive the following error, once again for every function in resistor class (except for the constructor, mysteriously):

1>rparser.cpp(301): error C2264: 'Resistor::setIndex' : error in function definition or declaration; function not called

I receive the following error:

1> resistor.cpp(7): error C2084: function 'Resistor::Resistor(int,std::string,double,int [])' already has a body
1>          resistor.h(25) : see previous definition of '{ctor}'

With every single one of my class functions, even though in resistor.h I have don’t have any empty implementations:

Resistor.h:

class Resistor
{
private:
   int rIndex;
   double resistance; // resistance (in Ohms)
   string name; // C++ string holding the label
   int endpointNodeIDs[2]; // IDs of nodes it attaches to

public:    
   Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2]);

}

Resistor.cpp:

Resistor::Resistor(int rIndex_,string name_,double resistance_,int endpoints_[2])
{
    if (nodeArray[endpoints_[0]].addResistor(rIndex_) && NodeArray[endpoints_[1]].addResistor(rIndex_))
{
    rIndex = rIndex_;
    name = name_;
    resistance = resistance_;
    endpointNodeIDs[0] = endpoints_[0];
    endpointNodeIDs[1] = endpoints_[1];
}

return;
}

etc. for each of my class functions

Can anybody help me?

p.s. I also receive the following error, once again for every function in resistor class (except for the constructor, mysteriously):

1>rparser.cpp(301): error C2264: 'Resistor::setIndex' : error in function definition or declaration; function not called
  • Forum
  • Beginners
  • error c2084

error c2084

#include <Windows.h>
#include <iostream>
#include<conio.h>
#include<iomanip>
using namespace std;

void classRec(); void end(); void editRec(); void gotoxy(int x,int y);
;
void menu()
{
char ch;
do
{ cout<<«nnntMAIN MENU»;
cout<<«nnt1. CLASS RECORD»;
cout<<«nnt2. EDIT RECORDS»;
cout<<«nnt3. HELP»;
cout<<«nnt4. EXIT»;

cout<<«nntPlease Select Your Option (1-3): «;
k:
cin>> ch;

switch(ch)
{
case ‘1’: classRec();

break;
case ‘2’: editRec();
break;
case ‘3’: end();
break;
default :
gotoxy(8,15);
cout<<«Please enter a valid choice: «;
goto k;

}
}while(ch!=’3′);
system(«cls»);
system(«pause>0»);

}

I can’t run my program. It says that there’s an error,error C2084: function ‘void menu(void)’ already has a body. How can I solve this? Please help me. Thank you. =)

It would be more helpful if you showed the exact error the compiler produced. It will name one or more files, so we’ll need to those too (with their names).

Error 1 error C2084: function ‘void menu(void)’ already has a body c:userspaulinedocumentsvisual studio 2010projectsclassrecordclassrecordmenu.h 11

Please help me. I’m just a beginner in programming and I badly needed to finish this program. Thank you so much. =)

And what’s in menu.h?

And why is there no reference to menu.h in the posted code?

Last edited on

Topic archived. No new replies allowed.

Вопрос:

Я не мог понять, что мне нужно сделать, чтобы исправить эту ошибку или найти что-либо на этом веб-сайте. В основном я получаю ошибку C2084: функция “Калькулятор :: GUI :: GUI (void)” уже имеет тело. Все, что у меня есть, – это форма окна, называемая GUI, добавленная в приложение Win32, калькулятор.

В GUI.h:

#pragma once

namespace Calculator {

using namespace System;
using namespace System::ComponentModel;
using namespace System::Collections;
using namespace System::Windows::Forms;
using namespace System::Data;
using namespace System::Drawing;

/// <summary>
/// Summary for GUI
/// </summary>

public ref class GUI : public System::Windows::Forms::Form
{

void AddControls();
public:
GUI()
{
InitializeComponent();
//
//TODO: Add the constructor code here
//


}

и в GUI.cpp

#include "GUI.h"

namespace Calculator {

GUI::GUI()
{

}

void DrawButtons();
void DrawLabels();

void GUI::AddControls()
{
DrawButtons();
DrawLabels();
}

Я получил то, что хотел работать, поместив все в файл GUI.h, но хотел иметь код метода внутри.cpp файла.

Лучший ответ:

Измените заголовок следующим образом:

public ref class GUI : public System::Windows::Forms::Form
{

void AddControls();
public:
    GUI();
}

Вы видите, что заголовок должен содержать только декларации и вносить реализацию в cpp.

  • Forum
  • Beginners
  • error c2084

error c2084

#include <Windows.h>
#include <iostream>
#include<conio.h>
#include<iomanip>
using namespace std;

void classRec(); void end(); void editRec(); void gotoxy(int x,int y);
;
void menu()
{
char ch;
do
{ cout<<«nnntMAIN MENU»;
cout<<«nnt1. CLASS RECORD»;
cout<<«nnt2. EDIT RECORDS»;
cout<<«nnt3. HELP»;
cout<<«nnt4. EXIT»;

cout<<«nntPlease Select Your Option (1-3): «;
k:
cin>> ch;

switch(ch)
{
case ‘1’: classRec();

break;
case ‘2’: editRec();
break;
case ‘3’: end();
break;
default :
gotoxy(8,15);
cout<<«Please enter a valid choice: «;
goto k;

}
}while(ch!=’3′);
system(«cls»);
system(«pause>0»);

}

I can’t run my program. It says that there’s an error,error C2084: function ‘void menu(void)’ already has a body. How can I solve this? Please help me. Thank you. =)

It would be more helpful if you showed the exact error the compiler produced. It will name one or more files, so we’ll need to those too (with their names).

Error 1 error C2084: function ‘void menu(void)’ already has a body c:userspaulinedocumentsvisual studio 2010projectsclassrecordclassrecordmenu.h 11

Please help me. I’m just a beginner in programming and I badly needed to finish this program. Thank you so much. =)

And what’s in menu.h?

And why is there no reference to menu.h in the posted code?

Last edited on

Topic archived. No new replies allowed.


Форум программистов Vingrad

> Ошибка 

:(

Опции темы

newnik

Новичок

Профиль
Группа: Участник
Сообщений: 2
Регистрация: 27.2.2011

Репутация: нет
Всего: нет

Код
#include "stdafx.h"
# include <stdio.h>
#include <stdlib.h>
#include <iostream>//Библиотека для ввода вывода
#include <conio.h>//<Библиотека для того, чтобы работала ф-я getch()
#define MAX 50
using namespace std;
struct Node//node - по-английски узел. Здесб мы описываем структуру данных, которая является узлом списка
{
int info;//переменная info - почти как ячейка массива
Node* next;//указатель на следующий улемент списка
};

Node *start, *end;//указатели на начало и конец списка

void Add(int a)//ф-я добавления элемента в список
{
if (start==NULL)//если список пуст
{
start=new Node;//то создаем первый элемент
end=start;//если в списке всего один элемент, то его начало и конец совпадают
start->info=a;//саполняем эту единственную ячейку 
start->next=NULL;//обозначаем, что на этом элементе список заканчивается
}
else//а если список не пуст, то добавляем в конец списка
{
end->next=new Node;//создает элемент в конце списка
end=end->next;//переходим к нему
end->info=a;//заполняем его ниформацией
end->next=NULL;//и обозначаем, что на нем список заканчивается
}
}

void Print()//ф-я вывода списка на экран
{
cout<<"Spisok : ";
Node* cur = start;//устанавляем указатель на начало списка
while (cur!=NULL)//и начинаем "скакать" по нему до тех пор, пока он не закончится
{
cout<<cur->info<<" ";//выводим информация из текущей ячейки списка
cur=cur->next;//и переходим к следующей
}
cout<<endl;//затем переходим на экране на следующую строку
}

int main()
{
int n; cout<<"N="; cin>>n;//ввод N - кол-ва чисел
int* m = new int[n];//создаем динамически массив из N чисел
for (int i=0; i<n; i++)//в цикле вводим этот массив
{
cout<<"m["<<i<<"]=";
cin>>m[i];
}
start=NULL; end=NULL;
{
for (int i=0; i<n; i++)//в цикле 
Add(m[i]);//добавляем элементы в список при каждом вызове ф-и Add
Print();//вызываем ф-ю вывода списка на экран
}
}
int main (void)
{
int list[MAX];
int next[MAX];
int prev[MAX];
int end=0;
int begin=0;
for (int i=0; i<MAX; i++)
{ list[i]=next[i]=prev[i]=0;   }
printf("Input the number of elements: ");
int n=0;
scanf("%d",&n);
prev[0]=-1;
printf("Input elements of list: ");
int count=0;
for (int i=0; i<n; i++) 
{    scanf("%d",&list[i]);
next[i]=i+1;
prev[i]=i-1;
count++;
}
prev[0]=-1;
next[count]=-1;
begin=0;
end=count-1;
printf("Elements of list from the end to begin: ");
int temp=end;
do {        printf("%d ",list[temp]);
temp=prev[temp];
      } while (prev[temp]!=-1);
printf("%d n",list[temp]);
system("PAUSE");
return 0;   }

В этой программе пишет такую ошибку

Цитата
Error    1    error C2084: function ‘int main(void)’ already has a body    66    

Модератор: Не забываем пользоваться кнопочкой «Код»

Это сообщение отредактировал(а) bsa — 27.2.2011, 19:24

volatile

Эксперт
****

Профиль
Группа: Завсегдатай
Сообщений: 2107
Регистрация: 7.1.2011

Репутация: 16
Всего: 85

Цитата(newnik @  27.2.2011,  16:40 Найти цитируемый пост)
function ‘int main(void)’ already has a body    

Перевести не пробовали.
Функция main уже имеет тело.
У вас более одной функции main.

newnik

Новичок

Профиль
Группа: Участник
Сообщений: 2
Регистрация: 27.2.2011

Репутация: нет
Всего: нет

Цитата(volatile @ 27.2.2011,  16:49)
Цитата(newnik @  27.2.2011,  16:40 Найти цитируемый пост)
function ‘int main(void)’ already has a body    

Перевести не пробовали.
Функция main уже имеет тело.
У вас более одной функции main.

и что тогда сделать надо?

volatile

Эксперт
****

Профиль
Группа: Завсегдатай
Сообщений: 2107
Регистрация: 7.1.2011

Репутация: 16
Всего: 85

Цитата(newnik @  27.2.2011,  16:51 Найти цитируемый пост)
и что тогда сделать надо? 

Надо выбрать какую вы будете использовать.
Другую либо удалить, либо переимеовать.  smile 

bsa

Эксперт
****

Профиль
Группа: Модератор
Сообщений: 9185
Регистрация: 6.4.2006
Где: Москва, Россия

Репутация: 85
Всего: 196

newnik, рекомендую почитать Оформление кода

———————

Правильно заданный вопрос — половина ответа
Отзывы о работе модератора.



















Правила форума «C/C++: Для новичков»
JackYF
bsa

Запрещается!

1. Публиковать ссылки на вскрытые компоненты

2. Обсуждать взлом компонентов и делиться вскрытыми компонентами

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

  • FAQ раздела лежит здесь!

Если Вам понравилась атмосфера форума, заходите к нам чаще! С уважением, JackYF, bsa.

0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | C/C++: Для новичков | Следующая тема »

Возможно, вам также будет интересно:

  • Insurgency ошибка steam validation rejected
  • Insurgency sandstorm ошибка при запуске
  • Insurgency sandstorm ошибка античита
  • Insurgency sandstorm ошибка unreal
  • Insufficient privileges ошибка стим

  • Понравилась статья? Поделить с друзьями:
    0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

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