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?
-
How did the function run without the return 0.
-
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
8,48816 gold badges52 silver badges82 bronze badges
asked Feb 14, 2014 at 20:17
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 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.
answered Feb 14, 2014 at 20:24
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.
answered Feb 14, 2014 at 20:29
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 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

asked Dec 23, 2015 at 19:48
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 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.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

asked Dec 23, 2015 at 19:48
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 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.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 |
|
Ответы с готовыми решениями: Программа которая выдает платформу компьютера выдает ошибку interface uses При решении программа выдаёт значение функции, равное 0 или выдаёт ошибку. Что не так? long Fact(short…
У меня не выдает ошибку, но программа действует не так как я хочу. Глаза должны двигаться за мышкой,но этого не происход 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 |
|||
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 |
|||||||||||
поправил, появился новый вопрос, почему у меня из исходного текстовика улетел весь текст? и во второй не прошло не одной записи? Добавлено через 8 минут
заменил имя файла, но во второй должна записаться строка:
подскажите почему ничего не происходит?
0 |
|
DrOffset 16466 / 8966 / 2198 Регистрация: 30.01.2014 Сообщений: 15,567 |
||||
|
09.02.2014, 23:40 |
6 |
|||
|
подскажите почему ничего не происходит? У вас std::string stroc первый раз объявлена внутри условия else, по правилам С++ ее время жизни ограничено блоком. Ниже вы создали еще одну (другую!) переменную stroc, она естественно пуста. Поправить можно перенеся объявление выше:
1 |
|
strannik11 2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
||||
|
10.02.2014, 13:37 [ТС] |
7 |
|||
|
поправил так как вы посоветовали, но запись почему то так и не происходит, не могу понять почему?
0 |
|
DrOffset 16466 / 8966 / 2198 Регистрация: 30.01.2014 Сообщений: 15,567 |
||||||||
|
10.02.2014, 15:11 |
8 |
|||||||
|
поправил так как вы посоветовали, но запись почему то так и не происходит, не могу понять почему? Ошибка та же. Объявление должно быть одно, а у вас их опять два.
заменить на
1 |
|
2 / 2 / 0 Регистрация: 03.02.2014 Сообщений: 28 |
|
|
10.02.2014, 15:26 [ТС] |
9 |
|
DrOffset, спасибо вам большое за советы, но эту ошибку исправил уже сам)) очень помогли мне. Добавлено через 4 минуты
0 |
|
DrOffset 16466 / 8966 / 2198 Регистрация: 30.01.2014 Сообщений: 15,567 |
||||
|
10.02.2014, 19:47 |
10 |
|||
|
как мне сделать так что бы моя программа не прибавляла в счетчике повторные слова, что бы например, слово «привет» считалось 1 раз, а потом программа пропускала бы его и шла дальше. Мне кажется самый просто способ для вас это использовать std::set. Добавлять туда слова из файла, дубликаты отсеятся.
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
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. 😉
Почему программа при работе выдает ошибку ‘INVALID POINTER OPERATION’ и работает потом как надо?
Уберите лишний и проблема решена.
