This my main function:
void main(int argc, char **argv)
{
if (argc >= 4)
{
ProcessScheduler *processScheduler;
std::cout <<
"Running algorithm: " << argv[2] <<
"\nWith a CSP of: " << argv[3] <<
"\nFilename: " << argv[1] <<
std::endl << std::endl;
if (argc == 4)
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3])
);
}
else
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3]),
atoi(argv[4]),
atoi(argv[5])
);
}
processScheduler -> LoadFile(argv[1]);
processScheduler -> RunProcesses();
GanntChart ganntChart(*processScheduler);
ganntChart.DisplayChart();
ganntChart.DisplayTable();
ganntChart.DisplaySummary();
system("pause");
delete processScheduler;
}
else
{
PrintUsage();
}
}
The error I get when I compile is this:
Application.cpp:41:32: error: ‘::main’ must return ‘int’
It’s a void function how can I return int and how do I fix it?
Michael
3,0937 gold badges39 silver badges83 bronze badges
asked Nov 2, 2016 at 14:05
3
Try doing this:
int main(int argc, char **argv)
{
// Code goes here
return 0;
}
The return 0;
returns a 0 to the operating system which means that the program executed successfully.
answered Nov 2, 2016 at 14:07
MichaelMichael
3,0937 gold badges39 silver badges83 bronze badges
5
C++ requires main()
to be of type int
.
answered Nov 2, 2016 at 14:18
Nick PaviniNick Pavini
3123 silver badges15 bronze badges
3
Function is declared as int main(..);
, so change your void
return value to int
, and return 0
at the end of the main function.
answered Nov 2, 2016 at 14:14
renonszrenonsz
5711 gold badge4 silver badges17 bronze badges
- Forum
- Beginners
- ‘main’ must return ‘int’
‘main’ must return ‘int’
Hey there
Whenever I compile this (see below) with gcc on Cygwin it returns with:
test.cpp:25: error: ‘main’ must return ‘int’;
Here is the source code
|
|
The error message is trying to tell you that main must return int.
i.e. Line 21 should be int main()
and at the end of your program you must return 0; // obviously only if the program executed successfully
return 0; is superfluous — main (and only main) returns 0 by default when the end of the function is reached.
For people who are new to programming who may not know that it is a good habbit to get into. Also, although somwhat a small amount, it makes the code more readable.
This can be confusing since some compilers allow void main()
and you see examples that use it in books and on the web ALL the time (by people who should know better). By the official rules of C++ though, it is wrong.
Topic archived. No new replies allowed.
c++
This my main function:
void main(int argc, char **argv)
{
if (argc >= 4)
{
ProcessScheduler *processScheduler;
std::cout <<
"Running algorithm: " << argv[2] <<
"\nWith a CSP of: " << argv[3] <<
"\nFilename: " << argv[1] <<
std::endl << std::endl;
if (argc == 4)
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3])
);
}
else
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3]),
atoi(argv[4]),
atoi(argv[5])
);
}
processScheduler -> LoadFile(argv[1]);
processScheduler -> RunProcesses();
GanntChart ganntChart(*processScheduler);
ganntChart.DisplayChart();
ganntChart.DisplayTable();
ganntChart.DisplaySummary();
system("pause");
delete processScheduler;
}
else
{
PrintUsage();
}
}
The error I get when I compile is this:
Application.cpp:41:32: error: ‘::main’ must return ‘int’
It’s a void function how can I return int and how do I fix it?
Tags:
c++
This my main function:
void main(int argc, char **argv)
{
if (argc >= 4)
{
ProcessScheduler *processScheduler;
std::cout <<
"Running algorithm: " << argv[2] <<
"\nWith a CSP of: " << argv[3] <<
"\nFilename: " << argv[1] <<
std::endl << std::endl;
if (argc == 4)
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3])
);
}
else
{
processScheduler = new ProcessScheduler(
argv[2],
atoi(argv[3]),
atoi(argv[4]),
atoi(argv[5])
);
}
processScheduler -> LoadFile(argv[1]);
processScheduler -> RunProcesses();
GanntChart ganntChart(*processScheduler);
ganntChart.DisplayChart();
ganntChart.DisplayTable();
ganntChart.DisplaySummary();
system("pause");
delete processScheduler;
}
else
{
PrintUsage();
}
}
The error I get when I compile is this:
Application.cpp:41:32: error: ‘::main’ must return ‘int’
It’s a void function how can I return int and how do I fix it?
713
People also ask
How do you fix error Main must return int?
Function is declared as int main(..); , so change your void return value to int , and return 0 at the end of the main function.
What does Error main must return int mean?
With C++ and C, the main function must be declared as an int, and therefore must return an int. In your code, you had changed the main function to a void, returning an error. Try changing void main() to int main() and add a line at the end of your function that returns 0.
What is the error main ()?
These are errors generated when the executable of the program cannot be generated. This may be due to wrong function prototyping, incorrect header files. One of the most common linker error is writing Main() instead of main().
Why void main is not used in C++?
In C++ the default return type of main is void, i.e. main() will not return anything. But, in C default return type of main is int, i.e. main() will return an integer value by default. In C, void main() has no defined(legit) usage, and it can sometimes throw garbage results or an error.
3 Answers
Try doing this:
int main(int argc, char **argv)
{
// Code goes here
return 0;
}
The return 0;
returns a 0 to the operating system which means that the program executed successfully.
133
C++ requires main()
to be of type int
.
5
Function is declared as int main(..);
, so change your void
return value to int
, and return 0
at the end of the main function.
1
>>‘::main’ must return ‘int’
тут компилятор в качестве К.О. указывает, что main() по стандарту должна возвращать int
- Показать ответ
- Ссылка
Ответ на:
комментарий
от alex_custov 05.09.10 00:04:16 MSD
Ответ на:
комментарий
от sudo-s 05.09.10 00:07:11 MSD
#include <iostream>
using namespace std;
int main ()
{
cout << «text»;
cin.get();
return 0;
}
- Показать ответ
- Ссылка
Ответ на:
комментарий
от Heretique 05.09.10 00:07:38 MSD
Ответ на:
комментарий
от sudo-s 05.09.10 00:11:04 MSD
return 0; не обязательно.
Booster ★★
(05.09.10 11:31:34 MSD)
- Ссылка
Ответ на:
комментарий
от sudo-s 05.09.10 00:07:11 MSD
Вы когда-нибудь поймёте, что вторую строчку лучше трогать)))
return 0; не обязательно.
Да, кстати, стандарт одобряэ ) Справедливо только для main.
- Ссылка
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
cout << "text";
cin.get();
return EXIT_SUCCESS;
}
unisky ★★
(05.09.10 12:53:40 MSD)
- Показать ответ
- Ссылка
Ответ на:
комментарий
от unisky 05.09.10 12:53:40 MSD
Ответ на:
комментарий
от m4n71k0r 05.09.10 13:48:33 MSD
дооо…ещё cstdlib туда лепить)))))
более академично: влияет только на препроцессор, что при современных процессорах не имеет значения, ничего лишнего не линкуется же… и вдруг через полсотни лет, когда уже все забудут про цпп, кто-то задастся вопросом — почему именно 0
^_^
unisky ★★
(05.09.10 15:08:14 MSD)
- Показать ответ
- Ссылка
Ответ на:
комментарий
от sudo-s 05.09.10 00:11:04 MSD
И тут я понял, чем не угодил kdevelop из соседнего топика.
Pavval ★★★★★
(05.09.10 16:58:56 MSD)
- Ссылка
Ответ на:
комментарий
от unisky 05.09.10 15:08:14 MSD
Ну лично я собираюсь через 50 лет программировать нанитов и манипулировать генами. … если конечно ресурсы планеты не закончатся и наша цивилизация не войдёт в тёмную эпоху деградации и развитого каннибализма )))
- Показать ответ
- Ссылка
Ответ на:
комментарий
от m4n71k0r 05.09.10 18:03:57 MSD
> Ну лично я собираюсь через 50 лет программировать нанитов и манипулировать генами. … если конечно ресурсы планеты не закончатся и наша цивилизация не войдёт в тёмную эпоху деградации и развитого каннибализма )))
на D++? =)
korvin_ ★★★★★
(05.09.10 18:46:27 MSD)
- Ссылка
Ответ на:
комментарий
от annulen 05.09.10 18:47:28 MSD
это g++ написанный на elisp, очевидно же!
- Ссылка
Ответ на:
комментарий
от annulen 05.09.10 18:47:28 MSD
G++ — сокращение от GNU C++. Пишем в Емаксе, сохранием в цпп, потом g++ /path/to/file/filename и получаем бинарник.
sudo-s ★
(06.09.10 03:44:46 MSD)
- Показать ответ
- Ссылка
Ответ на:
комментарий
от sudo-s 06.09.10 03:44:46 MSD
и получаем бинарник.
А если мне кроскомпилировать нужно? g++ [path/to/file] уже не прокатит (даже в емаксе)
quasimoto ★★★★
(06.09.10 10:37:38 MSD)
- Показать ответ
- Ссылка
Ответ на:
комментарий
от quasimoto 06.09.10 10:37:38 MSD
>g++ [path/to/file] уже не прокатит
o rly? заменяешь g++ на имя твоего кросс-компилятора, и все дела
annulen ★★★★★
(06.09.10 11:15:41 MSD)
- Показать ответ
- Ссылка
Ответ на:
комментарий
от annulen 06.09.10 11:15:41 MSD
Ну я как-то привык в ключиках всё писать — в Makefile-ах.
quasimoto ★★★★
(06.09.10 11:17:59 MSD)
- Ссылка
Вы не можете добавлять комментарии в эту тему. Тема перемещена в архив.
The error message is trying to tell you that main must return int. return 0; is superfluous – main (and only main) returns 0 by default when the end of the function is reached. For people who are new to programming who may not know that it is a good habbit to get into.
Does main have to return int?
The main function should always return an int. In environments that have an operating system (OS), the OS starts your program running. The integer value returned from main provides a way for your program to return a value to the OS indicating whether the program succeeded, failed, or generated some integer result.
Does main return int in C?
void main(void) : It denotes empty, it means no value is returned which is also accepted in our programming language. 2. int main() : It return some value like Zero or Non-Zero. The main function is C always return an integer value and it goes as an exit code to the program which executed it.
What is difference between void main and int main?
The void main() indicates that the main() function will not return any value, but the int main() indicates that the main() can return integer type data. When our program is simple, and it is not going to terminate before reaching the last line of the code, or the code is error free, then we can use the void main().
Why do we return 0 in C?
These status codes are just used as a convention for a long time in C language because the language does not support the objects and classes, and exceptions. return 0: A return 0 means that the program will execute successfully and did what it was intended to do.
What should main return C?
What should main() return in C and C++? The return value for main is used to indicate how the program exited. If the program execution was normal, a 0 return value is used. Abnormal termination(errors, invalid inputs, segmentation faults, etc.) is usually terminated by a non-zero return.
What is the purpose of int main void?
Int main(void) is used in C to restrict the function to take any arguments, if you dont put void in those brackets, the function will take ANY number of arguments you supply at call.
Why is Main an int?
The short answer, is because the C++ standard requires main() to return int . As you probably know, the return value from the main() function is used by the runtime library as the exit code for the process. Both Unix and Win32 support the concept of a (small) integer returned from a process after it has finished.
What is int main void?
int main() indicates that the main function can be called with any number of parameters or without any parameter. On the other hand, int main(void) indicates that the main function will be called without any parameter #include int main() { static int i = 5; if (–i){ printf(“%d “, i); main(10); } }
Why void main is wrong in C?
It’s non-standard. The int returned by main() is a way for a program to return a value to the system that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make void main() legal. Even if your compiler accepts void main() avoid it in any case. It’s incorrect.
What’s the difference between int main and void main?
A conforming implementation may provide more versions of main (), but they must all have return type int. The int returned by main () is a way for a program to return a value to “the system” that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make “void main ()” legal C++ or legal C.
Is it legal to write void main ( ) in C?
*/ } A conforming implementation may provide more versions of main (), but they must all have return type int. The int returned by main () is a way for a program to return a value to “the system” that invokes it. On systems that doesn’t provide such a facility the return value is ignored, but that doesn’t make “void main ()” legal C++ or legal C.
Why do I get an error with void main ( )?
However, with Xcode I’m getting an error that says, “error: ‘::main’ must return ‘int’”. Can anyone toss me some insight into why I’m getting this error, and how I may be able to correct it so that the compiler accepts main() as ‘void’?
What does’main’must return’int’in C + +?
The main function of a C++ program must return an int. This means that unlike some other programming languages, you cannot have the following: void main() {} void main(args) {} long main() {}. If you do this, you have not written a C++ program, and all respectable, ISO standard-compliant C++ compilers will reject the above code.