Меню

Ошибка undefined reference to winmain

This error occurs when the linker can’t find WinMain function, so it is probably missing. In your case, you are probably missing main too.

Consider the following Windows API-level program:

#define NOMINMAX
#include <windows.h>

int main()
{
    MessageBox( 0, "Blah blah...", "My Windows app!", MB_SETFOREGROUND );
}

Now let’s build it using GNU toolchain (i.e. g++), no special options. Here gnuc is just a batch file that I use for that. It only supplies options to make g++ more standard:

C:test> gnuc x.cpp

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000003        (Windows CUI)

C:test> _

This means that the linker by default produced a console subsystem executable. The subsystem value in the file header tells Windows what services the program requires. In this case, with console system, that the program requires a console window.

This also causes the command interpreter to wait for the program to complete.

Now let’s build it with GUI subsystem, which just means that the program does not require a console window:

C:test> gnuc x.cpp -mwindows

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:test> _

Hopefully that’s OK so far, although the -mwindows flag is just semi-documented.

Building without that semi-documented flag one would have to more specifically tell the linker which subsystem value one desires, and some Windows API import libraries will then in general have to be specified explicitly:

C:test> gnuc x.cpp -Wl,-subsystem,windows

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:test> _

That worked fine, with the GNU toolchain.

But what about the Microsoft toolchain, i.e. Visual C++?

Well, building as a console subsystem executable works fine:

C:test> msvc x.cpp user32.lib
x.cpp

C:test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               3 subsystem (Windows CUI)

C:test> _

However, with Microsoft’s toolchain building as GUI subsystem does not work by default:

C:test> msvc x.cpp user32.lib /link /subsystem:windows
x.cpp
LIBCMT.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartu
p
x.exe : fatal error LNK1120: 1 unresolved externals

C:test> _

Technically this is because Microsoft’s linker is non-standard by default for GUI subsystem. By default, when the subsystem is GUI, then Microsoft’s linker uses a runtime library entry point, the function where the machine code execution starts, called winMainCRTStartup, that calls Microsoft’s non-standard WinMain instead of standard main.

No big deal to fix that, though.

All you have to do is to tell Microsoft’s linker which entry point to use, namely mainCRTStartup, which calls standard main:

C:test> msvc x.cpp user32.lib /link /subsystem:windows /entry:mainCRTStartup
x.cpp

C:test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               2 subsystem (Windows GUI)

C:test> _

No problem, but very tedious. And so arcane and hidden that most Windows programmers, who mostly only use Microsoft’s non-standard-by-default tools, do not even know about it, and mistakenly think that a Windows GUI subsystem program “must” have non-standard WinMain instead of standard main. In passing, with C++0x Microsoft will have a problem with this, since the compiler must then advertize whether it’s free-standing or hosted (when hosted it must support standard main).

Anyway, that’s the reason why g++ can complain about WinMain missing: it’s a silly non-standard startup function that Microsoft’s tools require by default for GUI subsystem programs.

But as you can see above, g++ has no problem with standard main even for a GUI subsystem program.

So what could be the problem?

Well, you are probably missing a main. And you probably have no (proper) WinMain either! And then g++, after having searched for main (no such), and for Microsoft’s non-standard WinMain (no such), reports that the latter is missing.

Testing with an empty source:

C:test> type nul >y.cpp

C:test> gnuc y.cpp -mwindows
c:/program files/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined referen
ce to `WinMain@16'
collect2: ld returned 1 exit status

C:test> _

This error occurs when the linker can’t find WinMain function, so it is probably missing. In your case, you are probably missing main too.

Consider the following Windows API-level program:

#define NOMINMAX
#include <windows.h>

int main()
{
    MessageBox( 0, "Blah blah...", "My Windows app!", MB_SETFOREGROUND );
}

Now let’s build it using GNU toolchain (i.e. g++), no special options. Here gnuc is just a batch file that I use for that. It only supplies options to make g++ more standard:

C:test> gnuc x.cpp

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000003        (Windows CUI)

C:test> _

This means that the linker by default produced a console subsystem executable. The subsystem value in the file header tells Windows what services the program requires. In this case, with console system, that the program requires a console window.

This also causes the command interpreter to wait for the program to complete.

Now let’s build it with GUI subsystem, which just means that the program does not require a console window:

C:test> gnuc x.cpp -mwindows

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:test> _

Hopefully that’s OK so far, although the -mwindows flag is just semi-documented.

Building without that semi-documented flag one would have to more specifically tell the linker which subsystem value one desires, and some Windows API import libraries will then in general have to be specified explicitly:

C:test> gnuc x.cpp -Wl,-subsystem,windows

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:test> _

That worked fine, with the GNU toolchain.

But what about the Microsoft toolchain, i.e. Visual C++?

Well, building as a console subsystem executable works fine:

C:test> msvc x.cpp user32.lib
x.cpp

C:test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               3 subsystem (Windows CUI)

C:test> _

However, with Microsoft’s toolchain building as GUI subsystem does not work by default:

C:test> msvc x.cpp user32.lib /link /subsystem:windows
x.cpp
LIBCMT.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartu
p
x.exe : fatal error LNK1120: 1 unresolved externals

C:test> _

Technically this is because Microsoft’s linker is non-standard by default for GUI subsystem. By default, when the subsystem is GUI, then Microsoft’s linker uses a runtime library entry point, the function where the machine code execution starts, called winMainCRTStartup, that calls Microsoft’s non-standard WinMain instead of standard main.

No big deal to fix that, though.

All you have to do is to tell Microsoft’s linker which entry point to use, namely mainCRTStartup, which calls standard main:

C:test> msvc x.cpp user32.lib /link /subsystem:windows /entry:mainCRTStartup
x.cpp

C:test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               2 subsystem (Windows GUI)

C:test> _

No problem, but very tedious. And so arcane and hidden that most Windows programmers, who mostly only use Microsoft’s non-standard-by-default tools, do not even know about it, and mistakenly think that a Windows GUI subsystem program “must” have non-standard WinMain instead of standard main. In passing, with C++0x Microsoft will have a problem with this, since the compiler must then advertize whether it’s free-standing or hosted (when hosted it must support standard main).

Anyway, that’s the reason why g++ can complain about WinMain missing: it’s a silly non-standard startup function that Microsoft’s tools require by default for GUI subsystem programs.

But as you can see above, g++ has no problem with standard main even for a GUI subsystem program.

So what could be the problem?

Well, you are probably missing a main. And you probably have no (proper) WinMain either! And then g++, after having searched for main (no such), and for Microsoft’s non-standard WinMain (no such), reports that the latter is missing.

Testing with an empty source:

C:test> type nul >y.cpp

C:test> gnuc y.cpp -mwindows
c:/program files/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined referen
ce to `WinMain@16'
collect2: ld returned 1 exit status

C:test> _

This error occurs when the linker can’t find WinMain function, so it is probably missing. In your case, you are probably missing main too.

Consider the following Windows API-level program:

#define NOMINMAX
#include <windows.h>

int main()
{
    MessageBox( 0, "Blah blah...", "My Windows app!", MB_SETFOREGROUND );
}

Now let’s build it using GNU toolchain (i.e. g++), no special options. Here gnuc is just a batch file that I use for that. It only supplies options to make g++ more standard:

C:test> gnuc x.cpp

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000003        (Windows CUI)

C:test> _

This means that the linker by default produced a console subsystem executable. The subsystem value in the file header tells Windows what services the program requires. In this case, with console system, that the program requires a console window.

This also causes the command interpreter to wait for the program to complete.

Now let’s build it with GUI subsystem, which just means that the program does not require a console window:

C:test> gnuc x.cpp -mwindows

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:test> _

Hopefully that’s OK so far, although the -mwindows flag is just semi-documented.

Building without that semi-documented flag one would have to more specifically tell the linker which subsystem value one desires, and some Windows API import libraries will then in general have to be specified explicitly:

C:test> gnuc x.cpp -Wl,-subsystem,windows

C:test> objdump -x a.exe | findstr /i "^subsystem"
Subsystem               00000002        (Windows GUI)

C:test> _

That worked fine, with the GNU toolchain.

But what about the Microsoft toolchain, i.e. Visual C++?

Well, building as a console subsystem executable works fine:

C:test> msvc x.cpp user32.lib
x.cpp

C:test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               3 subsystem (Windows CUI)

C:test> _

However, with Microsoft’s toolchain building as GUI subsystem does not work by default:

C:test> msvc x.cpp user32.lib /link /subsystem:windows
x.cpp
LIBCMT.lib(wincrt0.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartu
p
x.exe : fatal error LNK1120: 1 unresolved externals

C:test> _

Technically this is because Microsoft’s linker is non-standard by default for GUI subsystem. By default, when the subsystem is GUI, then Microsoft’s linker uses a runtime library entry point, the function where the machine code execution starts, called winMainCRTStartup, that calls Microsoft’s non-standard WinMain instead of standard main.

No big deal to fix that, though.

All you have to do is to tell Microsoft’s linker which entry point to use, namely mainCRTStartup, which calls standard main:

C:test> msvc x.cpp user32.lib /link /subsystem:windows /entry:mainCRTStartup
x.cpp

C:test> dumpbin /headers x.exe | find /i "subsystem" | find /i "Windows"
               2 subsystem (Windows GUI)

C:test> _

No problem, but very tedious. And so arcane and hidden that most Windows programmers, who mostly only use Microsoft’s non-standard-by-default tools, do not even know about it, and mistakenly think that a Windows GUI subsystem program “must” have non-standard WinMain instead of standard main. In passing, with C++0x Microsoft will have a problem with this, since the compiler must then advertize whether it’s free-standing or hosted (when hosted it must support standard main).

Anyway, that’s the reason why g++ can complain about WinMain missing: it’s a silly non-standard startup function that Microsoft’s tools require by default for GUI subsystem programs.

But as you can see above, g++ has no problem with standard main even for a GUI subsystem program.

So what could be the problem?

Well, you are probably missing a main. And you probably have no (proper) WinMain either! And then g++, after having searched for main (no such), and for Microsoft’s non-standard WinMain (no such), reports that the latter is missing.

Testing with an empty source:

C:test> type nul >y.cpp

C:test> gnuc y.cpp -mwindows
c:/program files/mingw/bin/../lib/gcc/mingw32/4.4.1/../../../libmingw32.a(main.o):main.c:(.text+0xd2): undefined referen
ce to `WinMain@16'
collect2: ld returned 1 exit status

C:test> _

Sklifasovsky

11 / 1 / 0

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

Сообщений: 61

1

06.01.2019, 14:35. Показов 4423. Ответов 3

Метки компилятор (Все метки)


Здраствуйте!

Помогите пожалуйста разобратся в моем франкенштейне =) База данных клиентов.
Компилятор (Dev-C++) ругается.
undefined reference to `WinMain’

Где допустил ошибку?

Код:

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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <string>
 
using namespace std;
 
 
 
struct clientData
{
    int accNum;
    char Sur[15];
    char Name[15];
    float balance;
};
 
void ADD(clientData mas[]);
void Del(clientData mas[],int Num);
void Show(clientData mas[]);
void Find(clientData mas[],int Num);
void Change(clientData mas[],int accNum,float balance);
void Dolj(clientData mas[]);
int Count(clientData mas[]);
 
 
 
void ADD(clientData mas[]){
bool b=false;
for(int i=0;i<100;i++)
{
    if(mas[i].accNum==-1) 
    {
        b=true;
        mas[i].accNum=i;
        cout<<"Enter Sur: ";
        cin>> mas[i].Sur;
        cout<<"Enter Name: ";
        cin>>  mas[i].Name; 
        cout<<"Enter balance: ";
        cin>>  mas[i].balance;   
        break;              
    }
}
if(b==false)cout<<"Base full, delete any element"<<endl;
}
 
 
 
 
void Del(clientData mas[],int Num)
{bool b=false;
for(int i=0;i<100;i++)
{
    if(mas[i].accNum==Num) 
    {
        b=true;
        mas[i].accNum=-1; 
        break;              
    }
}
if(b==false)cout<<"element do not found"<<endl;
}
 
 
void Show(clientData mas[])
{bool b=false;
for(int i=0;i<100;i++)
{
    if(mas[i].accNum>=0) 
    {
        b=true;
        cout<<"accNum: "<< mas[i].accNum<<endl;
        cout<<"Sur: "<< mas[i].Sur<<endl;
        cout<<"Name: "<<mas[i].Name<<endl; 
        cout<<"balance: "<< mas[i].balance<<endl;          
 
    }
}
if(b==false)cout<<"elements do not found";
}
 
void Find(clientData mas[],int Num)
{bool b=false;
for(int i=0;i<100;i++)
{
    if(mas[i].accNum==Num) 
    {
        b=true;
        cout<<"accNum: "<< mas[i].accNum<<endl;
        cout<<"Sur: "<< mas[i].Sur<<endl;
        cout<<"Name: "<<mas[i].Name<<endl; 
        cout<<"balance: "<< mas[i].balance<<endl;
        break;              
    }
}
if(b==false)cout<<"element do not found"<<endl;
}
 
void Change(clientData mas[],int Num,float balance){
    bool b=false;
    for(int i=0;i<100;i++)
    {
        if(mas[i].accNum==Num) 
        {
            b=true;
            mas[i].balance= balance; 
            break;              
        }
    }
    if(b==false)cout<<"element do not found"<<endl;
}
 
 
void Dolj(clientData mas[]){
    bool b=false;
    for(int i=0;i<100;i++)
    {
        if(mas[i].balance<0 && mas[i].accNum>=0) 
        {
            b=true;
            cout<<"accNum: "<< mas[i].accNum<<endl;
            cout<<"Sur: "<< mas[i].Sur<<endl;
            cout<<"Name: "<<mas[i].Name<<endl; 
            cout<<"balance: "<< mas[i].balance<<endl<<endl;                      
        }
    }
    if(b==false)cout<<"do not found"<<endl;
 
}
 
int Count (clientData mas[])
{
    bool b=false;int count=0;
    for(int i=0;i<100;i++)
    {
        if(mas[i].accNum!=-1) 
        {
            b=true;
            count++;                   
        }
    }
    return count;
}

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



0



Параллельный Кот

1904 / 826 / 350

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

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

06.01.2019, 14:40

2

Sklifasovsky, тип проекта какой выбрали? И чем является этот код? Если это должна была быть библиотека, то нужно выбрать соответствующий тип проекта. Если это приложение, то нужна точка входа, в данном случае WinMain.



0



Sklifasovsky

11 / 1 / 0

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

Сообщений: 61

06.01.2019, 16:18

 [ТС]

3

valen10, Мое задание —
Основываясь на этой структуре:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
struct clientData               //клиент
 
{
 
   int accNum;     //номер счёта
 
   char Sur[15];   //фамилия
 
   char Name[10];              //Имя
 
   float balance;  //Баланс (сумма на счету, или долг)
 
};

реализовать базу данных в виде массива. Должно быть главное меню со следующими операциями:

Добавить запись
Удалить запись
Вывести все записи (только те которые существуют)
Найти запись (по номеру счёта)
Изменить баланс счёта (введя номер счёта, и положительное или отрицательное значение – изменить сумму на введённое значение)
Вывести должников (все записи с отрицательным балансом)
Сосчитать записи (общее количество заполненных записей)
Выход (из программы)
Специальные требования:

Номер счёта, это индекс элемента в массиве.
Длина массива 100 элементов
Для каждой операции реализовать отдельную функцию.
Все функции поместить в отдельную библиотеку.
После выполнения любой операции заново выводить меню.



0



16469 / 8968 / 2199

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

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

06.01.2019, 20:05

4

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

в данном случае WinMain.

Ему нужна обычная функция main здесь.
Линкер ищет WinMain, но программист должен написать обычный main.



0



Code:Blocks forum,

 Here’s the information I left out in my original post.

 I am running Code::Blocks version 16.01 on Windows 7 Professional SP1
 The compiler I use is Mingw32 and search directories set to
 C:SDL2-2.0.5includeSDL.  There are no relative paths in my setup.

 When I build a simple «Hello World» program there are no errors and
 it runs successfully.  If I add #include <SDH.h> and try to build it
 again I get the error message ‘undefined reference to ‘WinMain@16’

  File name is main.cpp

#include <SDL.h>
#include <iostream>
using namespace std;

int main()
{
    cout << «Hello world!» << endl;
    return 0;
}

 BUILD LOG WITHOUT #include <SDL.h>

————— Build: Debug in SDL (compiler: GNU GCC Compiler)—————

 mingw32-g++.exe -Wall -std=c++11 -fexceptions -g -mwindows -std=c++11 -mwindows -IC:SDL2-2.0.5includeSDL2 -I»C:Program FilesCodeBlocksSDL» -IC:SDL2-2.0.5includeSDL2 -I»C:Program FilesCodeBlocksSDL» -c «C:Program FilesCodeBlocksSDLmain.cpp» -o objDebugmain.o
 mingw32-g++.exe -LC:SDL2-2.0.5lib -LC:SDL2-2.0.5lib -o binDebugSDL.exe objDebugmain.o  -lmingw32 -lSDL2main -lSDL2 -lmingw32 -lSDL2main -lSDL2 
 Output file is binDebugSDL.exe with size 1.01 MB
 Process terminated with status 0 (0 minute(s), 0 second(s))
 0 error(s), 0 warning(s) (0 minute(s), 0 second(s))

  BUILD LOG WITH #include <SDL.h>

————— Build: Debug in SDL (compiler: GNU GCC Compiler)—————

 mingw32-g++.exe -Wall -std=c++11 -fexceptions -g -mwindows -std=c++11 -mwindows -IC:SDL2-2.0.5includeSDL2 -I»C:Program FilesCodeBlocksSDL» -IC:SDL2-2.0.5includeSDL2 -I»C:Program FilesCodeBlocksSDL» -c «C:Program FilesCodeBlocksSDLmain.cpp» -o objDebugmain.o
 mingw32-g++.exe -LC:SDL2-2.0.5lib -LC:SDL2-2.0.5lib -o binDebugSDL.exe objDebugmain.o  -lmingw32 -lSDL2main -lSDL2 -lmingw32 -lSDL2main -lSDL2 
 C:/Program Files (x86)/CodeBlocks/MinGW/bin/../lib/gcc/mingw32/4.9.2/../../../libmingw32.a(main.o):main.c:(.text.startup+0xa7): undefined reference to `WinMain@16′
 collect2.exe: error: ld returned 1 exit status
 Process terminated with status 1 (0 minute(s), 0 second(s))
 2 error(s), 0 warning(s) (0 minute(s), 0 second(s))

  OTHER THINGS I HAVE TRIED

 There was a suggestions on the web regarding placing -mwindows as compiler
 flag which you can see in the Build logs.

 Select the checkbox  in Settings-> Compiler > Build options «Explicitly add currently compiling file’s directory to compiler search dirs».

 Closing and reopening Code:Blocks.

 Go to project > build option and put a check mark on «Have g++ follow the C++11 ISO C++ language standard [-std=c++11]».

 project —> build option Put check mark on » Have g++ follow the C++11 ISO C++ language standard [-std=c++11]»

 Any suggestions?

Jerry D.

I have seen posts about this problem before, and tried everything within them.

This code is for my Freshmen (9th grade) free class, and I am making a simple calculator with if/then statements. I have my first adding portion assembled, but when I try to compile/run it doesn’t work.

Here’s my code thus far.

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
#include <iostream.h>

using namespace std;

int add ( int x, int y )

{
{
  int typeofmath;


  cout<<"(1)Add/(2)Subtract/(3)Multiply/(4)Divide: ";
  cin>> typeofmath;
  cin.ignore();
  if ( typeofmath == 1 )
     { int x;
       int y;

  cout<<"Please enter the two numbers you want added: ";               //Goal: Figure out how the WinMain@16 error works/is/fix!!!
  cin>> x >> y;
  cin.ignore();
  cout<<"Your answer is "<< add ( x, y );
  cin.get();
}

int add ( int x, int y );

{
  return x + y;
}

}
}

Also, I have tried adding int main() and iostream.h

It doesnt work.

Last edited on

It looks like you accidentally made a windows application project, rather than a console project. This is why it is looking for the windows entry point ‘WinMain’, rather than the console entry point ‘main’.

I suggest you create a new project, being careful to select «Console Application», and then copy the source code over from the old project to the new one.

PS: What is your IDE? You should really be #including «iostream» rather than «iostream.h» these days. 😉

PPS: If I were you I would check your code — there seem to be a few stray curly braces.

PPPS: Don’t use «Console Application» if you use VC++, as that will be a huge hassle. Just make a new blank project instead.

Good point — the configuration wizard is annoying 😉
I don’t think Visual Studio has an «iostream.h» header file though, so I guess the OP has a different IDE. But maybe I’m wrong…

I love the configuration wizard! hehe. I hated it when I didn’t understand the precompiled header, though. :-S Not that I FULLY understand now. 😛

But true about the empty project. In Visual Studio, select Win32 Project, then in the Settings page select Empty Project. This way you’ll be free of the precomppiled header.

And yes, it does have iostream, sstream, etc.

I assumed a precompiled header was just a header file that got compiled before being included to speed up compile times.

And yes, it does have iostream, sstream, etc.

Lol, I know it has the standard header files :P. What I was saying is that my version of MSVCE 2010 definitely doesn’t have «iostream.h«, i.e. the old style header file with the ‘.h’ extension.

Last edited on

Doh! My bad. Did not catch that one.

Alright, I have re-done the code, and Ill include a bit more information this time.

I removed the .h, as it was useless. I tried using a different compiler (From the Code :: Blocks to DevC++) and both got similar errors. I have a feeling that it has to do with the int add (int x, int y) line of code, and the missing int main().

I am using the Code :: Blocks Compiler currently.

Also, creating a blank project did not fix the error, just caused confusion, as I could not create anything within the project.

Also, what is an IDE?

Included is the code, with a few of the stray curly braces removed 😛

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
#include <iostream>

using namespace std;

int add ( int x, int y);


{
{
  int typeofmath;


  cout<<"(1)Add/(2)Subtract/(3)Multiply/(4)Divide: ";
  cin>> typeofmath;
  cin.ignore();
  if ( typeofmath == 1 )

     { int x;
       int y;

  cout<<"Please enter the two numbers you want added: ";
  cin>> x >> y;
  cin.ignore();
  cout<<"Your answer is "<< add ( x, y );
  cin.get();
}

int add ( int x, int y );

{
  return x + y;
}

}
}

It stands for Integrated Development Environment. It is a piece of software which combines an editor (usually with syntax highlighting and code completion) with a compiler and linker, and often many other plugins for various purposes.

I am using the Code :: Blocks Compiler currently.

In fact, Code::Blocks is an IDE. The compiler it uses by default is called MinGW. The same is true for Dev C++, which, I stress, you should no longer be using as it is abandonware (unless you mean wxDev C++).

Without an entry point of some kind (int main for console applications, INT WinMain for windows applications etc.), you cannot create an executable application. What exactly are you trying to do?

Sorry for the long reply time, the schools network has been down and I could not get home access.

I am trying to build a calculator with if/then statements. There are easier ways to do it, but with the little amount I have been taught, I figured this would be a challenging process 😛

This is the first chunk, the adding portion. When I tried to compile it, I got the error.

So what can I do to fix the error? I need to declare a variable, such as int main or winmain, but I also need to include the x and y integers.

I stress, you should no longer be using as it is abandonware

I have uninstalled it and am back to Code::Blocks. I like the interface more too.

Also, I am on an age-old XP, not sure if that affects anything much.

Last edited on

XP is fine; it certainly won’t be causing these problems.

Good decision!

So as for your error, does your program have either a int main() function or a INT WINAPI WinMain(...) function?

So as for your error, does your program have either a int main() function or a INT WINAPI WinMain(…) function?

No it does not. The code is seen above ^ and that’s the complete first quarter. The only problem is that.

Also, again, sorry for the late response. With finals, this isn’t a HIGH priority, but still up there.

Thanks for all help given so far 😀

Also, again, sorry for the late response

No problem.

So you have no main function, or other entry point. You can’t compile an executable therefore. Are you trying to make a library or something?

I am trying to make a calculator using only if-then statements, with a few other bits thrown in.

This is the first 1/4th, and I already have the other 3 parts ready to add to the code, except I can’t get past this first error.

If you want to compile your code to a console program which runs, i.e. a .exe file, then you must have a main function. There is no other option. This is the console entry point. Without it you cannot define with which code your (console) program starts.

If all your code is in other functions, then just call them from main.

If you want these functions to be available to you when you write future programs, then you will need to compile your code into a static or dynamic library. These do not need an entry point.

Regards
-Xander314

Last edited on

Topic archived. No new replies allowed.

When linking against SDL2 using the default output from sdl2-config --libs after the most recent update, the following error occurs:

C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/9.3.0/../../../../x86_64-w64-mingw32/bin/ld.exe: C:/msys64/mingw64/bin/../lib/gcc/x86_64-w64-mingw32/9.3.0/../../../../x86_64-w64-mingw32/lib/../lib/libmingw32.a(lib64_libmingw32_a-crt0_c.o): in function `main':
D:/mingwbuild/mingw-w64-crt-git/src/mingw-w64/mingw-w64-crt/crt/crt0_c.c:18: undefined reference to `WinMain'
collect2.exe: error: ld returned 1 exit status

This did not occur prior to the most recent update. The problem appears to be that the new sdl2-config files for both MINGW64 and MINGW32 contain the following handler for --libs:

    --libs)
      echo -L${exec_prefix}/lib  -mwindows -lSDL2main -lmingw32 -lSDL2

Changing it to this line from the sdl2-config bundled with the official SDL2 mingw development package fixes the problem:

    --libs)
      echo -L${exec_prefix}/lib  -lmingw32 -lSDL2main -lSDL2 -mwindows

Since it looks like SDL generates sdl2-config, could this be related to a082f60?


Recommended Answers

Sounds like you created a windows console program but attempting to compile a Windows win32 api GUI program. win32 api programs have WinMain() instead of main() as in console programs.

Jump to Post

No, you didn’t ruin my day 🙂 Just mark the thread Solved and everything will be ok.

Jump to Post

All 6 Replies

Member Avatar


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster


9 Years Ago

Sounds like you created a windows console program but attempting to compile a Windows win32 api GUI program. win32 api programs have WinMain() instead of main() as in console programs.

Member Avatar

9 Years Ago

Err, my mistake.
I thought I had seen this error before.
I forgot to add the sourcefile with the main function in it.

Well, if the moderators want to delete this entire thread then feel free.

Hope I didn’t ruin anyones day.

Member Avatar


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster


9 Years Ago

No, you didn’t ruin my day 🙂 Just mark the thread Solved and everything will be ok.

Member Avatar

9 Years Ago

WinMain@16 usually apears when you try to compile some files, which doesn’t contain the main()/WinMain() function (starting point of the program). In your case, not including the souce file with the main() function in it was causing your troubles.

Member Avatar


Ege_1

0



Newbie Poster


9 Years Ago

I’m tryibg to use opencv in eclipse c++ and I get the same error but I have

main()

function.

I have the following result

**** Internal Builder is used for build               ****
g++ -IC:opencvbuildinclude -O0 -g3 -Wall -c -fmessage-length=0 -osrcmain.o ..srcmain.cpp
g++ -LC:opencvbuildx86vc10lib -LC:opencvbuildx86vc11lib -otest.exe srcmain.o -lopencv_core247 -lopencv_core247d -lopencv_highgui247 -lopencv_highgui247d -lopencv_imgproc247 -lopencv_imgproc247d
C:/MinGW/i686-pc-mingw32/lib/libmingw32.a(lib32_libmingw32_a-crt0_c.o):crt0_c.c:(.text+0x3c): undefined reference to `WinMain@16'
collect2.exe: error: ld returned 1 exit status
Build error occurred, build is stopped

Member Avatar


Ancient Dragon

5,243



Achieved Level 70



Team Colleague



Featured Poster


9 Years Ago

undefined reference to `WinMain@16′

That normally means you are compiling a MS-Windows GUI program but use main() instead of WinMain(). But I think you need to post code and the makefile so it can be tested. Does the esample program here compile correctly?

Edited

9 Years Ago
by Ancient Dragon


Reply to this topic

Be a part of the DaniWeb community

We’re a friendly, industry-focused community of developers, IT pros, digital marketers,
and technology enthusiasts meeting, networking, learning, and sharing knowledge.

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Ошибка undefined index fieldvalues
  • Ошибка undefined array key php