Меню

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,48816 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

250k42 gold badges422 silver badges621 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,7498 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

I have typed in the following code in Ubuntu using Emacs and compiled using the command line

#include <stdio.h>

int main(void)
{
  printf("Hello World!nn");
  return 0;
}

Having the void in the main function argument returns the following warning

helloworld.c: In function ‘main’:
helloworld.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

When I removed the «void» within the parenthesis the program compiled without any errors. What is incorrect in have main(void) in this program?

Compilation command is
gcc -Wall -ggdb helloworld.c -o hello

Edit:
This is the screenshot which I would like to share
enter image description here

asked Dec 23, 2015 at 19:48

Prasanna's user avatar

PrasannaPrasanna

3032 silver badges16 bronze badges

6

The error doesn’t have anything to do with the void in the signature of main() int main(void) is correct and is the way to define main() when you don’t need to handle command line arguments.

The error means that you defined int main(void) and you did not return a value from the function. Like this

#include <stdio.h>

int main(void) 
{
    printf("Hello World!n");    
}

This warning was removed for main() in newer versions of gcc because main() implicitly returns 0 when the program exits unless you indicate otherwise with exit() or an explict return from main().

Normal functions still trigger this warning and it helps in prevention of undefined behavior due to not returning from a function and trying to capture the return value.

answered Dec 23, 2015 at 19:51

Iharob Al Asimi's user avatar

Iharob Al AsimiIharob Al Asimi

52.4k6 gold badges59 silver badges96 bronze badges

2

The only way that warning could be for main() function is if you don’t have a return statement and you are compiling in C89/C90 mode.

Since C99, a return statement at the end of main() is not required and it’ll be assumed to return 0; if control returns from main()‘s end. So compile in c99 or C11 mode:

gcc -Wall -ggdb -std=c11 helloworld.c -o hello

which won’t trigger that warning. Or make sure you have return statement if you are compiling in c89/C90. Until recently (at least upto gcc 4.9), the default mode in gcc is gnu90. So you would get that warning withot a return statement if you don’t passstd=.

I presume you don’t actually have return 0; in your real code that produces this warning as it wouldn’t matter in what mode of C you are compiling it if you had an explicit return statement.

answered Dec 23, 2015 at 20:06

P.P's user avatar

P.PP.P

116k20 gold badges170 silver badges231 bronze badges

9

I have typed in the following code in Ubuntu using Emacs and compiled using the command line

#include <stdio.h>

int main(void)
{
  printf("Hello World!nn");
  return 0;
}

Having the void in the main function argument returns the following warning

helloworld.c: In function ‘main’:
helloworld.c:6:1: warning: control reaches end of non-void function [-Wreturn-type]
 }
 ^

When I removed the «void» within the parenthesis the program compiled without any errors. What is incorrect in have main(void) in this program?

Compilation command is
gcc -Wall -ggdb helloworld.c -o hello

Edit:
This is the screenshot which I would like to share
enter image description here

asked Dec 23, 2015 at 19:48

Prasanna's user avatar

PrasannaPrasanna

3032 silver badges16 bronze badges

6

The error doesn’t have anything to do with the void in the signature of main() int main(void) is correct and is the way to define main() when you don’t need to handle command line arguments.

The error means that you defined int main(void) and you did not return a value from the function. Like this

#include <stdio.h>

int main(void) 
{
    printf("Hello World!n");    
}

This warning was removed for main() in newer versions of gcc because main() implicitly returns 0 when the program exits unless you indicate otherwise with exit() or an explict return from main().

Normal functions still trigger this warning and it helps in prevention of undefined behavior due to not returning from a function and trying to capture the return value.

answered Dec 23, 2015 at 19:51

Iharob Al Asimi's user avatar

Iharob Al AsimiIharob Al Asimi

52.4k6 gold badges59 silver badges96 bronze badges

2

The only way that warning could be for main() function is if you don’t have a return statement and you are compiling in C89/C90 mode.

Since C99, a return statement at the end of main() is not required and it’ll be assumed to return 0; if control returns from main()‘s end. So compile in c99 or C11 mode:

gcc -Wall -ggdb -std=c11 helloworld.c -o hello

which won’t trigger that warning. Or make sure you have return statement if you are compiling in c89/C90. Until recently (at least upto gcc 4.9), the default mode in gcc is gnu90. So you would get that warning withot a return statement if you don’t passstd=.

I presume you don’t actually have return 0; in your real code that produces this warning as it wouldn’t matter in what mode of C you are compiling it if you had an explicit return statement.

answered Dec 23, 2015 at 20:06

P.P's user avatar

P.PP.P

116k20 gold badges170 silver badges231 bronze badges

9

2 / 2 / 0

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

Сообщений: 28

1

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

09.02.2014, 22:38. Показов 1803. Ответов 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



16466 / 8966 / 2198

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

Сообщений: 15,567

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

16466 / 8966 / 2198

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

Сообщений: 15,567

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

16466 / 8966 / 2198

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

Сообщений: 15,567

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

16466 / 8966 / 2198

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

Сообщений: 15,567

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



16466 / 8966 / 2198

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

Сообщений: 15,567

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



16466 / 8966 / 2198

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

Сообщений: 15,567

11.02.2014, 00:27

14

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

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

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



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

The code posted above compiled without error for me. Is it possible that you didn’t cut and paste the original code from your development environment exactly as it appears?

Errors like this usually come from a typo or something else that doesn’t belong somewhere, such as a stray semicolon.

[edit-gotta stop answering half asleep. 😉 ]

Now that I’ve looked carefully at what you did, I understand the problem.

First, you ran the command clang welcome.c. This created the executable file called hello. You should consider using the make command in the future.

Next, you ran the command ./welcome.c. This told the system to attempt to execute the source code file welcome.c. So, it did what it was told and then crashed and burned on the 4th line of the source code file.

Instead, you want to execute the executable file, ./welcome, not welcome.c. C source code files are not intended to be executed directly. They need to be compiled and the executable files generated.

If this answers your question, please click on the check mark to accept. Let’s keep up on forum maintenance. 😉

0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

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

А вот еще интересные материалы:

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Insufficient privileges ошибка стим
  • Insufficient permission to access file ошибка