Меню

Fatal error lnk1120 1 unresolved externals c ошибка

What is causing this error? I google’d it and first few solutions I found were that something was wrong with the library and the main function but both seem to be fine in my problem, I even retyped both! What could be causing this?

This might be helpful:

MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol WinMain@16 referenced in function __tmainCRTStartup

#include <iostream>
using namespace std;
int main()
{
    const double A = 15.0, 
                 B = 12.0, 
                 C = 9.0;
    double aTotal, bTotal, cTotal, total;
    int numSold;

    cout << "Enter The Number of Class A Tickets Sold: ";
    cin >> numSold;
    aTotal = numSold * A;

    cout << "Enter The Number of Class B Tickets Sold: ";
    cin >> numSold;
    bTotal = numSold * B;

    cout << "Enter The Number of Class C Tickets Sold: ";
    cin >> numSold;
    cTotal = numSold * C;

    total = aTotal + bTotal + cTotal;

    cout << "Income Generated" << endl;
    cout << "From Class A Seats $" << aTotal << endl;
    cout << "From Class B Seats $" << bTotal << endl;
    cout << "From Class C Seats $" << cTotal << endl;
    cout << "-----------------------" << endl;
    cout << "Total Income: " << total << endl;

    return 0;
}

asked Sep 14, 2011 at 2:58

Howdy_McGee's user avatar

Howdy_McGeeHowdy_McGee

10.3k29 gold badges109 silver badges185 bronze badges

3

From msdn

When you created the project, you made the wrong choice of application
type. When asked whether your project was a console application or a
windows application or a DLL or a static library, you made the wrong
chose windows application (wrong choice).

Go back, start over again, go to File -> New -> Project -> Win32
Console Application -> name your app -> click next -> click
application settings.

For the application type, make sure Console Application is selected
(this step is the vital step).

The main for a windows application is called WinMain, for a DLL is
called DllMain, for a .NET application is called
Main(cli::array ^), and a static library doesn’t have a
main. Only in a console app is main called main

answered Sep 14, 2011 at 3:06

Drahakar's user avatar

DrahakarDrahakar

5,9366 gold badges42 silver badges58 bronze badges

1

I incurred this error once.

It turns out I had named my program ProgramMame.ccp instead of ProgramName.cpp

easy to do …

Hope this may help

answered Oct 25, 2012 at 15:58

Bob in SC's user avatar

Bob in SCBob in SC

1411 silver badge2 bronze badges

My problem was
int Main()
instead of
int main()

good luck

answered Nov 21, 2012 at 13:19

Mahika's user avatar

MahikaMahika

6622 gold badges11 silver badges21 bronze badges

Well it seems that you are missing a reference to some library. I had the similar error solved it by adding a reference to the #pragma comment(lib, «windowscodecs.lib»)

answered Apr 25, 2015 at 10:18

G droid's user avatar

G droidG droid

9565 gold badges13 silver badges36 bronze badges

In my case, the argument type was different in the header file and .cpp file. In the header file the type was std::wstring and in the .cpp file it was LPCWSTR.

Dharman's user avatar

Dharman

29.2k21 gold badges79 silver badges131 bronze badges

answered Sep 23, 2020 at 11:18

Vasantha Ganesh's user avatar

Vasantha GaneshVasantha Ganesh

4,3703 gold badges23 silver badges33 bronze badges

You must reference it. To do this, open the shortcut menu for the project in Solution Explorer, and then choose References. In the Property Pages dialog box, expand the Common Properties node, select Framework and References, and then choose the Add New Reference button.

answered Jul 5, 2016 at 10:06

Amir Touitou's user avatar

Amir TouitouAmir Touitou

2,9911 gold badge34 silver badges31 bronze badges

I have faced this particular error when I didn’t defined the main() function. Check if the main() function exists or check the name of the function letter by letter as Timothy described above or check if the file where the main function is located is included to your project.

answered Sep 21, 2016 at 9:02

funk's user avatar

funkfunk

2,1111 gold badge22 silver badges22 bronze badges

1

In my particular case, this error error was happening because the file which I’ve added wasn’t referenced at .vcproj file.

answered Nov 19, 2019 at 16:32

dbz's user avatar

dbzdbz

3717 silver badges22 bronze badges

In my case I got this error when I had declared a function under ‘public’ access specifier. Issue got resolved when I declared that function as private.

answered Mar 11, 2021 at 18:12

explorer2020's user avatar

I have encountered the same error. For me it turned out to be because I tried to implement an inline function in the .cpp file, instead of putting it in the header file, where the definition is. Therefore when I tried to include the header file and use the function, I got this error.

answered Nov 25, 2021 at 22:56

Kirk KD's user avatar

My case: I defined a prototype of the class de-constructor, but forgot to define the body.

class SomeClass {
    ~SomeClass(); //error
};

class SomeClass {
    ~SomeClass(){}; //no error
}

answered Jul 9, 2022 at 4:23

ChrisQIU's user avatar

In my case I had forgotten to add the main() function altogether.

answered Jul 29, 2022 at 5:34

Fractal Salamander's user avatar

  • Remove From My Forums
  • Question

  • 1>LIBCMTD.lib(wwincrt0.obj) : error LNK2019: unresolved external symbol _wWinMain@16 referenced in function ___tmainCRTStartup

    1>…….SerialDebugSerialTest.exe : fatal error LNK1120: 1 unresolved externals


    Is the 2nd one is consequence of the first?
    Althoug I’ve change all the properties as below, the above error are still exit.

    Configuration properties->
    -Character Set = Use multi-byte character set
    -Aditional dependencies = opengl32.lib glu32.lib ws2_32.lib
    -Subsytem = Windows (/SUBSYSTEM:WINDOWS)
    -change the entry point to wWinMainCRTStartup

    What else i need to change to stop the errors?pls help

Answers

  • Then I think I would try a reinstallation of Visual Studio Express.


    David Wilkinson | Visual C++ MVP

    • Marked as answer by

      Friday, February 26, 2010 9:41 AM

Дан код GitHub
При попытке компиляции выдает это

1>------ Build started: Project: SimpleLang, Configuration: Debug Win32 ------
1>  Parser.cpp
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:UsersDanielDocumentsGitHubSimpleLangDebugSimpleLang.exe : fatal error LNK1120: 1 unresolved externals
2>------ Build started: Project: Tests, Configuration: Debug Win32 ------
2>  Parser_GetType.cpp
2>Parser_GetType.obj : error LNK2019: unresolved external symbol "public: static class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> > __cdecl Parser::GetType(class std::basic_string<char,struct std::char_traits<char>,class std::allocator<char> >)" (?GetType@Parser@@SA?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@V23@@Z) referenced in function "private: virtual void __thiscall ParserTest_identifer_Test::TestBody(void)" (?TestBody@ParserTest_identifer_Test@@EAEXXZ)
2>C:UsersDanielDocumentsGitHubSimpleLangDebugTests.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 2 failed, 1 up-to-date, 0 skipped ==========

I followed this Instructions to compile ffmpeg x64 for UWP, but I got the following error:

BEGIN ./ffconf.jNjZgZMl.c 1 int main(void){ return 0; } END ./ffconf.jNjZgZMl.c cl -nologo -MD -DWINAPI_FAMILY=WINAPI_FAMILY_APP -D_WIN32_WINNT=0x0A00 -c -Fo./ffconf.HqaC4Hfy.o ./ffconf.jNjZgZMl.c ffconf.jNjZgZMl.c /d/Working_Space/GitHub/FFmpegInterop/ffmpeg/compat/windows/mslink -APPCONTAINER WindowsApp.lib -nologo -out:./ffconf.hSEPEeZV.exe ./ffconf.HqaC4Hfy.o LINK : error LNK2001: unresolved external symbol _mainCRTStartup C:Program Files (x86)Windows Kits10lib10.0.16299.0umx64WindowsApp.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'X86' C:Program Files (x86)Microsoft Visual Studio 14.0VClibstoreamd64MSVCRT.lib : warning LNK4272: library machine type 'x64' conflicts with target machine type 'X86' ./ffconf.hSEPEeZV.exe : fatal error LNK1120: 1 unresolved externals C compiler test failed.

Could anyone help me on this issue?

  • Forum
  • Beginners
  • fatal error LNK1120: 1 unresolved extern

fatal error LNK1120: 1 unresolved externals

So I am constructing my final for my C++ class, and I am cruising along, but then I get this weird error message that I have no idea what it means.

1>—— Build started: Project: Final Redux, Configuration: Debug Win32 ——
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:UsersDuckdocumentsvisual studio 2010ProjectsFinal ReduxDebugFinal Redux.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Any help would be great.

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
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
  #include<iostream>
#include<string>
#include<ctime>
#include<cstdlib>
///////////////////////////////////////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////Variables///////////////////////////////////////////////////////
using namespace std;
int randomNumber;
int Monster();
int num;
int monsterNum;

///////////////////////////////////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////////////////////////////////

int main(){
string input = "a";
int room = 1;

	while (input.compare("quit")!=0){

		switch (room){

			

		case 1:

cout<<"                    Terrorist Toad of the Mushroom Kingdomnnnn";		
cout << "Your name is Toad.n";
cout<< "You were assigned a top secret mission deep in the land of the Bomb-ombs.nnn";
cout<<"Your squad deserted you, left you to die. You decide to strike backn";
cout<<"You are now... TERRORIST TOAD"<<endl;
cout<<"Type 'west', 'east', 'north', and 'south' to navigate these desolate lands"<<endl;


		

			cout << "You are at the downed helicopternYou can go east or west or northn";
			getline(cin, input);

			if (input.compare("west") != 0)
				room = 2;
			else if (input.compare("east") != 0)
				room = 5;
			else if (input.compare("north") != 0)
				room = 6;
			else if (input.compare("south") != 0)
				cout << "Nope" << endl;

			break;


		case 2:

			cout << "You are in a homen You can go west or north or eastn" << endl;
			getline(cin, input);

			if (input.compare("south") != 0)
				cout << "Nope" << endl;
			else if (input.compare("west") != 0)
				room = 3;
			else if (input.compare("east") != 0)
				cout << "Nope" << endl;
			else if (input.compare("north") != 0)
				room = 4;

			

			break;
		case 3:
			


			cout << "You are on the shoren You can only go eastn" << endl;
			getline(cin, input);
			if (input.compare("east") != 0)
				cout << "Nope " << endl;
			else if (input.compare("south") != 0)
				room = 2;
			else if (input.compare("west") != 0)
				room = 4;
				
			else if (input.compare("north") != 0)
				cout << "Nope " << endl;


			break;
		case 4:

		


			cout << "You are in a parking lot. It kinda smells, you can go south or eastn" << endl;
			getline(cin, input);
			if (input.compare("south") != 0)
				room = 2;
			else if (input.compare("west") != 0)
				cout << "Nope" << endl;
			else if (input.compare("north") != 0)
				cout << "Nope" << endl;
			else if (input.compare("east") != 0)
				room = 6;
			break;


		case 5:
			


			
			
			
			cout << "You are in a Hospital You can go north or westn" << endl;
			getline(cin, input);
			if (input.compare("east") != 0)
				cout<<"Nope"<<endl;
			else if (input.compare("south") != 0)
				cout << "Nope" << endl;
			else if (input.compare("west") != 0)
				room = 1; 
			else if (input.compare("north") != 0)
				room = 7;
			
			

			break;

		case 6:
			



			
			
			cout << "You are in a Hotel You can go east or west or southn" << endl;
			getline(cin, input);
			if (input.compare("west") != 0)
				room = 4;
			else if (input.compare("south") != 0)
				room = 1;
			else if (input.compare("east") != 0)
				room = 7;
			else if (input.compare("north") != 0)
				cout << "Nope" << endl;


			

			break;

		case 7:
			

	
			

			
		cout << "You are in the Armory You can go east or north or west or southn" << endl;
			getline(cin, input);
			if (input.compare("west") != 0)
				room = 1;
			else if (input.compare("south") != 0)
				room = 5;
			else if (input.compare("west") != 0)
				room = 6;
			else if (input.compare("north") != 0)
				room = 10;

			

			break;

		case 8:
			


			if (monsterNum == 1)
				inventory[0] = "Ruby";
			else if (monsterNum == 2)
				inventory[1] = "Emerald";
			else if (monsterNum == 3)
				inventory[2] = "Diamond";
			else if (monsterNum == 4)
				inventory[3] = "Sapphire";
			else if (monsterNum == 5)
				inventory[4] = "Gold";

			cout << "Look out! There are bad guys. You have no choice but to fightnIn order to battle the president, you need the lucky dicenYou can go north or westn" << endl;
			Monster();

			getline(cin, input);
			if (input.compare("west") != 0)
				room = 7;
			else if (input.compare("south") != 0)
				cout << "Nope" << endl;
			else if (input.compare("west") != 0)
				cout << "Nope" << endl;
			else if (input.compare("north") != 0)
				room = 9;
			

			

			break;

		case 9:
			


			
			
			cout << "You are in the at the US Castle, You need to have the lucky dice! You can only go eastn" << endl;
			getline(cin, input);
			if (input.compare("west") != 0)
				room = 1;
			else if (input.compare("south") != 0)
				cout << "Nope" << endl;
			else if (input.compare("west") != 0)
				cout << "Nope" << endl;
			else if (input.compare("north") != 0)
				cout << "Nope" << endl;

			

			break;

		case 10:
			

			
			cout << "Welcome to Bass Pro! n" << endl;
			getline(cin, input);
			if (input.compare("west") != 0)
				room = 1;
			else if (input.compare("south") != 0)
				cout << "Nope" << endl;
			else if (input.compare("west") != 0)
				cout << "Nope" << endl;
			else if (input.compare("north") != 0)
				cout << "Nope" << endl;

			break;

		}


		}

	}


int Monster(){



	

		
		srand(static_cast<unsigned> (time(0)));
		randomNumber = rand();
		num = (randomNumber % 100) + 1;


		cout << "Theres a bad guy he has a " << endl;


		if (num > 5 && num <= 10){
			cout << "Tank" <<endl;
			return 1;
		}
		else if (num > 11 && num <= 15){
			cout << "Rocket Launcher" << endl;
			return 2;
		}
		
		else if (num > 16 && num <= 30){
			cout << "Machine Gun" << endl;
			return 3;
		}
			
		else if (num > 31 && num <= 50){
			cout << "Pistol" << endl;
			return 4;
		}
		else if (num > 51 && num <= 100){
			cout << "Knife" << endl;
			return 5;
		}
}

Which kind of project did you select?

CPP file
and an Empty Project

Plss try again.

Create project->Empty project.
Then add item->.cpp file.

Copy the code and paste.

add a line string inventory[5]; any where between main and line 20.

Build and run.

Last edited on

I tried that, and nothing happened, same error.

http://stackoverflow.com/questions/11247699/lnk2019-unresolved-external-symbol-main-referenced-in-function-tmaincrtstar

Topic archived. No new replies allowed.

Member Avatar

11 Years Ago

This program is to enter the scores, get the grades, and display the result.
However, I get a fatal error LNK1120: 1 unresolved externals
Does anyone know how to solve this problem?

#include <iostream>
#include <iomanip>
using namespace std;

// Function prototype
void letter(double score, double resultNum, char grade); //recieve grade
double calc_average(double sum, double num);
char grade[10];
double score[10];

double resultNum = 0;
int i = 1; // for visual appeal
int total_times =1;
double avg = 0;
double sum = 0;
double high = 0;
double low = 100;

double jjj;

int main()
{
	do
	{
		cout << "Enter result " << i << " (or -1 if no more results) ";
		cin >> score[i];
		jjj = score[i];
		if(score[i]!=-1)
		{
			sum=sum+jjj; //save inputs before continuing
			if (jjj>high)
				high = jjj; //check for high grades

			if (jjj<low)
				low = jjj; //check for low grades

			resultNum++; //used to divide average
			
			letter(score[i], resultNum, grade[i]); //recieve grade
			i++;
			total_times = i;
		}
	}while (score[i] !=-1);

	////////////////////////////////////////////////////////
	cout << "nThe list of the results and grades are: " << endl; 

	for ( i= 1; i < total_times; i++)

		cout << "Result " << i << ": " << score[i] << "t  Grade: " << grade[i] << endl;
		
	//////////////////////////////////////////////////////////

	//calc_average function for beautiful clean code
	cout << "nThe Average of the results = " << calc_average(sum,resultNum) << endl;
	cout << "The Lowest of the results = " << low << endl; 
	cout << "The Highest of the results = " << high << endl;
} 

double calc_average(double sum, double num)
{
	return (sum/num);
}

void letter(double score, double resultNum, int i)
{
	if (score<60)
	{
		cout << "Result " << resultNum << " is a Un" << endl;
		grade[i] = 'U';
	}
	if (score>=60 && score<70)
	{
		cout << "Result " << resultNum << " is a Cn" << endl;
		grade[i] = 'C';
	}
	if (score>=70 && score<90)
	{
		cout << "Result " << resultNum << " is a Bn" << endl;
		grade[i] = 'B';
	}
	if (score>=90)
	{
		cout << "Result " << resultNum << " is a An" << endl;
		grade[i] = 'A';
	}
}

Edited

11 Years Ago
by chuyauchi because:

n/a


Recommended Answers

that error means the linker cannot find some or all of the libraries it needs to do its job, you’ll need to check your compiler/linker documentation and installation to figure out how to make those known.

Jump to Post

All 6 Replies

Member Avatar


jwenting

1,855



duckman



Team Colleague


11 Years Ago

that error means the linker cannot find some or all of the libraries it needs to do its job, you’ll need to check your compiler/linker documentation and installation to figure out how to make those known.

Member Avatar

11 Years Ago

Addition error message:

1>test.obj : error LNK2019: unresolved external symbol «void __cdecl letter(double,double,char)» (?letter@@YAXNND@Z) referenced in function _main
1>c:usersadministratordocumentsvisual studio 2010ProjectstestDebugtest.exe : fatal error LNK1120: 1 unresolved externals


========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Member Avatar

11 Years Ago

#include <iostream>
#include <iomanip>
using namespace std;

// Function prototype
 char grade[10];
double score[10];

double resultNum = 0;
int i = 1; // for visual appeal
int total_times =1;
double avg = 0;
double sum = 0;
double high = 0;
double low = 100;

double jjj;
double calc_average(double sum, double num)
{
    return (sum/num);
}

void letter(double score, double resultNum, int i)
{
    if (score<60)
    {
        cout << "Result " << resultNum << " is a Un" << endl;
        grade[i] = 'U';
    }
    if (score>=60 && score<70)
    {
        cout << "Result " << resultNum << " is a Cn" << endl;
        grade[i] = 'C';
    }
    if (score>=70 && score<90)
    {
        cout << "Result " << resultNum << " is a Bn" << endl;
        grade[i] = 'B';
    }
    if (score>=90)
    {
        cout << "Result " << resultNum << " is a An" << endl;
        grade[i] = 'A';
    }

}


int main()
{
    do
    {
        cout << "Enter result " << i << " (or -1 if no more results) ";
        cin >> score[i];
        jjj = score[i];
        if(score[i]!=-1)
        {
            sum=sum+jjj; //save inputs before continuing
            if (jjj>high)
                high = jjj; //check for high grades

            if (jjj<low)
                low = jjj; //check for low grades

            resultNum++; //used to divide average

            letter(score[i], resultNum, grade[i]); //recieve grade
            i++;
            total_times = i;
        }
    }while (score[i] !=-1);

    ////////////////////////////////////////////////////////
    cout << "nThe list of the results and grades are: " << endl; 

    for ( i= 1; i < total_times; i++)

        cout << "Result " << i << ": " << score[i] << "t  Grade: " << grade[i] << endl;

    //////////////////////////////////////////////////////////

    //calc_average function for beautiful clean code
    cout << "nThe Average of the results = " << calc_average(sum,resultNum) << endl;
    cout << "The Lowest of the results = " << low << endl; 
    cout << "The Highest of the results = " << high << endl;
        return 0;
}

Edited

9 Years Ago
by Nick Evan because:

Fixed formatting

Member Avatar

11 Years Ago

Edited

11 Years Ago
by chuyauchi because:

n/a

Member Avatar

11 Years Ago

#include <iostream>
#include <iomanip>
using namespace std;

// Function prototype
 char grade[10];
double score[10];

double resultNum = 0;
int i = 1; // for visual appeal
int total_times =1;
double avg = 0;
double sum = 0;
double high = 0;
double low = 100;

double jjj;
double calc_average(double sum, double num)
{
    return (sum/num);
}

void letter(double score, double resultNum, int i)
{
    if (score<60)
    {
        cout << "Result " << resultNum << " is a Un" << endl;
        grade[i] = 'U';
    }
    if (score>=60 && score<70)
    {
        cout << "Result " << resultNum << " is a Cn" << endl;
        grade[i] = 'C';
    }
    if (score>=70 && score<90)
    {
        cout << "Result " << resultNum << " is a Bn" << endl;
        grade[i] = 'B';
    }
    if (score>=90)
    {
        cout << "Result " << resultNum << " is a An" << endl;
        grade[i] = 'A';
    }

}


int main()
{
    do
    {
        cout << "Enter result " << i << " (or -1 if no more results) ";
        cin >> score[i];
        jjj = score[i];
        if(score[i]!=-1)
        {
            sum=sum+jjj; //save inputs before continuing
            if (jjj>high)
                high = jjj; //check for high grades

            if (jjj<low)
                low = jjj; //check for low grades

            resultNum++; //used to divide average

            letter(score[i], resultNum, i); //recieve grade
            i++;
            total_times = i;
        }
    }while (score[i] !=-1);

    ////////////////////////////////////////////////////////
    cout << "nThe list of the results and grades are: " << endl; 

    for ( i= 1; i < total_times; i++)

        cout << "Result " << i << ": " << score[i] << "t  Grade: " << grade[i] << endl;

    //////////////////////////////////////////////////////////

    //calc_average function for beautiful clean code
    cout << "nThe Average of the results = " << calc_average(sum,resultNum) << endl;
    cout << "The Lowest of the results = " << low << endl; 
    cout << "The Highest of the results = " << high << endl;
    system("pause");
        return 0;
}

Edited

9 Years Ago
by Nick Evan because:

Fixed formatting

Member Avatar

11 Years Ago

Thank you very much. You solved my problem.


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 / 0

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

Сообщений: 3

1

06.06.2009, 23:50. Показов 72427. Ответов 19


Создал новый проект в visual c++ запускаю пустой проект а при запуске выдает
Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup MSVCRTD.lib
Error 2 fatal error LNK1120: 1 unresolved externals C:Documents and Settingsfirst_zeeМои документыVisual Studio 2005Projects1Debug1.exe
мои действия
1 обшарил весь нет
2 перепробовал все варианты
3 даже переустановил вижул
4……жутко матерился

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



0



Заказ софта

343 / 188 / 21

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

Сообщений: 863

07.06.2009, 00:04

2

Что значит «запускаю пустой проэкт». Вы пытаетесь скомпилировать пустоту ?



0



0 / 0 / 0

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

Сообщений: 3

07.06.2009, 00:07

 [ТС]

3

даже не пустоту не компилирует(обычно и пустоту компилировал
)



0



125 / 123 / 0

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

Сообщений: 766

07.06.2009, 00:29

4

в каждой программе должна быть функция main, ругается, что ее нет



0



Search..

Заказ софта

343 / 188 / 21

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

Сообщений: 863

07.06.2009, 00:40

5

Вот Вам пример простейшей программы:

C++
1
2
3
4
5
6
7
8
#include <stdio.h> /* Для того, чтобы функция printf могла работать */
 
int main(int argc, char * argv []) /* Main должен быть в любой программе! */
{ /* Открываем тело функции Main */
    printf("Hello World!n"); /* Функция printf печатает сообщение на экран */
 
    return 0; /* Возвращаем нулевое значение операционке */
} /* Закрываем тело функции Main */

Добавлено через 4 минуты 32 секунды
Во-первых, компилятор не может компилировать пустоту.
Во-вторых, компилятор выдает сообщение об ошибке из-за того, что Вы пытаетесь откомпилировать пустоту. Этой ошибкой компилятор пытается у Вас спросить примерно это: «ЧТО МНЕ КОМПИЛИРОВАТЬ ?! ТЫ ЖЕ НИЧЕГО НЕ НАПИСАЛ!!!».



0



first_zee

0 / 0 / 0

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

Сообщений: 3

07.06.2009, 12:10

 [ТС]

6

хорошо допустим хотел зто

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include<iostream>
#include<windows.h>
using namespace std;
void main()
{
    for(;;)
    {
    POINT a;
    GetCursorPos(&a);
    Sleep(100);
    cout<<a.x<<' '<<a.y;
    if(a.x<500)
        break;
    }
 
};



0



125 / 123 / 0

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

Сообщений: 766

07.06.2009, 13:22

7

я рад за тебя! пропиши в свойствах проекта точку входа — функцию main



0



3 / 3 / 1

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

Сообщений: 9

07.06.2009, 20:31

8

Лучший ответ Сообщение было отмечено как решение

Решение

По моему такая ошибка возникает когда пытаешься запустить консольное приложение в проекте другого типа, т.е. Win32 Project, а не Win32 Console Project
(в Visual Studio по крайней мере)



3



125 / 123 / 0

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

Сообщений: 766

07.06.2009, 21:08

9

возникает. а все потому, что процедуры входа по-разному описаны



0



I.B.

1 / 1 / 0

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

Сообщений: 48

04.02.2010, 20:54

10

Доброго времени суток … прошу помощи вот по такому вопросу … читаю книгу Юрия Щупака Win32 API … там есть пример программы hello, world … и вот компилятор выдаёт мне две ошибки

Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup MSVCRTD.lib

Error 2 fatal error LNK1120: 1 unresolved externals C:UsersSTRELOKDocumentsVisual Studio 2008ProjectsHello World 1DebugHello World 1.exe

вот исходник:

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
#include <windows.h> 
 
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdLine)
{
    HWND hMainWnd;
    char classname[] = "MyClass";
    MSG msg;
    WNDCLASSEX wc;
    wc.cbSize           = sizeof(wc);
    wc.style            = CS_HREDRAW|CS_VREDRAW;
    wc.lpfnWndProc      = WndProc;
    wc.cbClsExtra       = 0;
    wc.cbWndExtra       = 0;
    wc.hInstance        = hInstance;
    wc.hIcon            = LoadIcon(NULL, IDI_APPLICATION);
    wc.hCursor          = LoadCursor(NULL, IDC_ARROW);
    wc.hbrBackground    = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.lpszMenuName     = NULL;
    wc.lpszClassName    = classname;
    wc.hIconSm          = LoadIcon(NULL, IDI_APPLICATION);
 
 
    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, "Cannot register class", "Error", MB_OK);
        return 0;
    }
    
    hMainWnd = CreateWindow(classname, "new", WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 
        CW_USEDEFAULT, 0, (HWND)NULL, (HMENU)NULL, (HINSTANCE)hInstance, NULL);
 
    if(!hMainWnd)
    {
        MessageBox(NULL, "Cannot create window", "Error", MB_OK);
        return 0;
    }
 
    ShowWindow(hMainWnd, nCmdLine);
 
    while(GetMessage(&msg, NULL, 0, 0))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
 
    return msg.wParam;
}
 
 
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hDC;
    PAINTSTRUCT ps;
    RECT rect;
 
    switch (uMsg)
    {
    case WM_PAINT:
        hDC = BeginPaint(hWnd, &ps);
        GetClientRect(hWnd, &rect);
        DrawText(hDC, (LPCSTR)"Hello World 1", -1, &rect, DT_SINGLELINE|DT_CENTER|DT_VCENTER);
 
        EndPaint(hWnd, &ps);
        break;
    
    case WM_CLOSE:
        DestroyWindow(hWnd);
        break;
        
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
 
    default:
        return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }
 
    return 0;
}

в свойствах ставлю мультибайт … среда 2008 года …

Заранее спасибо )



1



Search..

Заказ софта

343 / 188 / 21

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

Сообщений: 863

05.02.2010, 03:17

11

Используется Unicode-версия класса окна (WNDCLASSEX), а полю ws.lpszClassName присваиваешь ANSI строку . . . Еще есть некоторые ошибки. Так будет правильнее:

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
//////////////////////////////////////////////////////////////////////////////
#define _UNICODE
#define UNICODE
//////////////////////////////////////////////////////////////////////////////
#include <windows.h> 
#include <tchar.h>
//////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
//////////////////////////////////////////////////////////////////////////////
 
INT WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR lpCmdLine, INT iShowCmd)
{
    MSG msg;
    HWND hMainWnd;
    WNDCLASSEX wc;
 
    //////////////////////////////////////////////////////////////////////////////
    wc.cbSize               = sizeof(wc);
    wc.cbClsExtra           = NULL;
    wc.cbWndExtra           = NULL;
    wc.hbrBackground        = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.hCursor              = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
    wc.hIcon                = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
    wc.hIconSm              = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
    wc.hInstance            = hInstance;
    wc.lpfnWndProc          = WndProc;
    wc.lpszClassName        = _T("MyClass");
    wc.lpszMenuName         = NULL;
    wc.style                = CS_HREDRAW | CS_VREDRAW;
    //////////////////////////////////////////////////////////////////////////////
 
 
    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, _T("Cannot register class"), _T("Error"), MB_ICONSTOP);
        return FALSE;
    }
 
    hMainWnd = CreateWindowEx(NULL, _T("MyClass"), _T("new"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 
        CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
 
    if(!hMainWnd)
    {
        MessageBox(NULL, _T("Cannot create window"), _T("Error"), MB_ICONSTOP);
        return FALSE;
    }
 
    ShowWindow(hMainWnd, iShowCmd);
 
    while(GetMessage(&msg, NULL, NULL, NULL))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
 
    return msg.wParam;
}
 
 
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hDC;
    PAINTSTRUCT ps;
    RECT rect;
 
    switch (uMsg)
    {
    case WM_PAINT:
        hDC = BeginPaint(hWnd, &ps);
        //////////////////////////////////////////////////////////////////////////////
        GetClientRect(hWnd, &rect);
        DrawText(hDC, _T("Hello World !"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        //////////////////////////////////////////////////////////////////////////////
        EndPaint(hWnd, &ps);
        break;
 
    case WM_CLOSE:
        DestroyWindow(hWnd);
        break;
 
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
 
    default:
        return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }
 
    return FALSE;
}



0



23 / 23 / 5

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

Сообщений: 130

05.02.2010, 12:35

12

Лучший ответ Сообщение было отмечено как решение

Решение

Цитата
Сообщение от I.B.
Посмотреть сообщение

Доброго времени суток … прошу помощи вот по такому вопросу … читаю книгу Юрия Щупака Win32 API … там есть пример программы hello, world … и вот компилятор выдаёт мне две ошибки

Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup MSVCRTD.lib

Error 2 fatal error LNK1120: 1 unresolved externals C:UsersSTRELOKDocumentsVisual Studio 2008ProjectsHello World 1DebugHello World 1.exe

в свойствах ставлю мультибайт … среда 2008 года …

Заранее спасибо )

У тебя в настройках стоит консольный проект. Отключи или переключи на виндосовский в Properties -> Linker -> System -> SubSystem -> NotSet (или Windows)



4



1 / 1 / 0

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

Сообщений: 48

05.02.2010, 23:52

13

nazavrik, спасибо )))



0



I.B.

1 / 1 / 0

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

Сообщений: 48

07.02.2010, 00:17

14

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

Используется Unicode-версия класса окна (WNDCLASSEX), а полю ws.lpszClassName присваиваешь ANSI строку . . . Еще есть некоторые ошибки. Так будет правильнее:

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
//////////////////////////////////////////////////////////////////////////////
#define _UNICODE
#define UNICODE
//////////////////////////////////////////////////////////////////////////////
#include <windows.h> 
#include <tchar.h>
//////////////////////////////////////////////////////////////////////////////
LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM);
//////////////////////////////////////////////////////////////////////////////
 
INT WINAPI _tWinMain(HINSTANCE hInstance, HINSTANCE, LPTSTR lpCmdLine, INT iShowCmd)
{
    MSG msg;
    HWND hMainWnd;
    WNDCLASSEX wc;
 
    //////////////////////////////////////////////////////////////////////////////
    wc.cbSize               = sizeof(wc);
    wc.cbClsExtra           = NULL;
    wc.cbWndExtra           = NULL;
    wc.hbrBackground        = (HBRUSH)GetStockObject(WHITE_BRUSH);
    wc.hCursor              = LoadCursor(NULL, MAKEINTRESOURCE(IDC_ARROW));
    wc.hIcon                = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
    wc.hIconSm              = LoadIcon(NULL, MAKEINTRESOURCE(IDI_APPLICATION));
    wc.hInstance            = hInstance;
    wc.lpfnWndProc          = WndProc;
    wc.lpszClassName        = _T("MyClass");
    wc.lpszMenuName         = NULL;
    wc.style                = CS_HREDRAW | CS_VREDRAW;
    //////////////////////////////////////////////////////////////////////////////
 
 
    if(!RegisterClassEx(&wc))
    {
        MessageBox(NULL, _T("Cannot register class"), _T("Error"), MB_ICONSTOP);
        return FALSE;
    }
 
    hMainWnd = CreateWindowEx(NULL, _T("MyClass"), _T("new"), WS_OVERLAPPEDWINDOW, CW_USEDEFAULT, 0, 
        CW_USEDEFAULT, 0, NULL, NULL, hInstance, NULL);
 
    if(!hMainWnd)
    {
        MessageBox(NULL, _T("Cannot create window"), _T("Error"), MB_ICONSTOP);
        return FALSE;
    }
 
    ShowWindow(hMainWnd, iShowCmd);
 
    while(GetMessage(&msg, NULL, NULL, NULL))
    {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
    }
 
    return msg.wParam;
}
 
 
LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam)
{
    HDC hDC;
    PAINTSTRUCT ps;
    RECT rect;
 
    switch (uMsg)
    {
    case WM_PAINT:
        hDC = BeginPaint(hWnd, &ps);
        //////////////////////////////////////////////////////////////////////////////
        GetClientRect(hWnd, &rect);
        DrawText(hDC, _T("Hello World !"), -1, &rect, DT_SINGLELINE | DT_CENTER | DT_VCENTER);
        //////////////////////////////////////////////////////////////////////////////
        EndPaint(hWnd, &ps);
        break;
 
    case WM_CLOSE:
        DestroyWindow(hWnd);
        break;
 
    case WM_DESTROY:
        PostQuitMessage(0);
        break;
 
    default:
        return DefWindowProc(hWnd, uMsg, wParam, lParam);
    }
 
    return FALSE;
}

Search, а для чего вы определили макрос юникод и везде где есть char-строки делаете преобразование типов? И почему два макроса?



0



23 / 23 / 5

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

Сообщений: 130

07.02.2010, 00:38

15

По поводу char-строк.

Макрос _T() работает так: если проект использует ANSI строки, то он оставляет строки без изменений, а если проект использует UNICODE строки, то он преобразовывает ANSI строку в UNICODE.

По умолчанию в последних версиях VS стоит «Use Unicode Character Set». Если ты переключил на «Use Multi-Byte Character Set» (а ты переключил ), то никакого преобразования нет. По факту избыточный код.



1



Айхрень…

306 / 176 / 7

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

Сообщений: 1,077

18.05.2010, 16:20

16

Хм… почитал тему, но вопрос собственно аналогичный вопросу топикстартера.

Вообще ситуация какая-то странная, толи перегрев, толит ещё что в голове у меня не так:

в проекте Visual Studio 2010 прописан Project Properties->CC++->General->Additional Include Directories = $(SolutionDir)list, вот, в данном каталоге лежат файлики mylist.h & mylist.cpp, в них расписаны шаблоны классов для динамических списков моего проекта.

Добавляю в эти файлики в заголовочный, допустим, функцию int vvv();, в файл исходного кода int vvv() {int i=123; return i;}, в итоге получаю:

1> adding resource. type:MANIFEST, name:2, language:0x0409, flags:0x30, size:2
1>DBFParser.obj : error LNK2019: unresolved external symbol «int __cdecl vvv(void)» (?vvv@@YAHXZ) referenced in function «protected: void __fastcall DBFParser::ParseString(char *,class myList<char *> *)» (?ParseString@DBFParser@@IAIXPADPAV?$myList@PAD@@@ Z)
1>C:UsersPADocumentsVisual Studio 2010ProjectsReestrConverterDebugDBFParser.dll : fatal error LNK1120: 1 unresolved externals

Видимо он не видит файлика cpp, это крайне печально, ему что, надо файлик lib собрать и законнектить? Я прочитал уже с десяток форумов, где-топишут про кодировку, где-топро либы… Что-то я подзапутался))



0



5 / 5 / 1

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

Сообщений: 42

19.05.2010, 20:57

17

first_zee
Доброго времени суток … прошу помощи вот по такому вопросу … читаю книгу Юрия Щупака Win32 API … там есть пример программы hello, world … и вот компилятор выдаёт мне две ошибки

Error 1 error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup MSVCRTD.lib

Error 2 fatal error LNK1120: 1 unresolved externals C:UsersSTRELOKDocumentsVisual Studio 2008ProjectsHello World 1DebugHello World 1.exe

ти какой проект создаеш Win32 Console Application, а нужно Win32 Project



0



10 / 10 / 3

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

Сообщений: 152

26.10.2010, 23:21

18

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

Win32 Console Application, а нужно Win32 Project

у меня и в Win32 project’e была та же ерунда..
когда я изменил в настройках подсистему, окошко заработало, но выводило бред
осталось найти где изменить кодировку



0



бжни

2473 / 1684 / 135

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

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

26.10.2010, 23:36

19

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

Видимо он не видит файлика cpp, это крайне печально, ему что, надо файлик lib собрать и законнектить? Я прочитал уже с десяток форумов, где-топишут про кодировку, где-топро либы… Что-то я подзапутался))

cpp в проект надо включать явно, либо через libу



0



-3 / 16 / 2

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

Сообщений: 151

22.09.2017, 14:34

20

Как логировать приложение если используется winmain?



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

22.09.2017, 14:34

20

На чтение 3 мин. Просмотров 75 Опубликовано 15.12.2019

число неразрешенных внешних идентификаторов number unresolved externals

Error LNK1120 сообщает количество неразрешенных ошибок внешних символов в текущей ссылке. Error LNK1120 reports the number of unresolved external symbol errors in the current link.

Каждый неразрешенный внешний символ сначала получает сообщение об ошибке LNK2001 или LNK2019 . Each unresolved external symbol first gets reported by a LNK2001 or LNK2019 error. Сообщение LNK1120 поступает последним и показывает количество ошибок неразрешенного символа. The LNK1120 message comes last, and shows the unresolved symbol error count.

Устранить эту ошибку не нужно. You don’t need to fix this error. Эта ошибка исчезает, когда вы исправляете все ошибки компоновщика LNK2001 и LNK2019 до того, как они попадают в выходные данные сборки. This error goes away when you correct all of the LNK2001 and LNK2019 linker errors before it in the build output. Всегда устранять проблемы, начиная с первой ошибки, о которой сообщается. Always fix issues starting at the first reported error. Более поздние ошибки могут быть вызваны более ранними версиями и исчезнуть при исправлении предыдущих ошибок. Later errors may be caused by earlier ones, and go away when the earlier errors are fixed.

При компиляции программы ошибок не вылетает. значит в коде ошибок нет. Но при попытке создания экзешника студия показывает 2 ошибки:

1. error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup

2. fatal error LNK1120: 1 unresolved externals

При работе с кодом на другой машине, нареканий у программы не возникает.

Напишите, пожалуйста, что необходимо сделать чтобы студия работала нормально (поподробнее для чайника) . И если нетрудно, опишите причины возникновения ошибок.

What is causing this error? I google’d it and first few solutions I found were that something was wrong with the library and the main function but both seem to be fine in my problem, I even retyped both! What could be causing this?

This might be helpful:

MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol WinMain@16 referenced in function __tmainCRTStartup

7 Answers 7

When you created the project, you made the wrong choice of application type. When asked whether your project was a console application or a windows application or a DLL or a static library, you made the wrong chose windows application (wrong choice).

Go back, start over again, go to File -> New -> Project -> Win32 Console Application -> name your app -> click next -> click application settings.

For the application type, make sure Console Application is selected (this step is the vital step).

The main for a windows application is called WinMain, for a DLL is called DllMain, for a .NET application is called Main(cli::array ^), and a static library doesn’t have a main. Only in a console app is main called main

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

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

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

  • Яшка сломя голову остановился исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного исправьте ошибки
  • Ясность цели позволяет целеустремленно добиваться намеченного где ошибка
  • Fatal error friday the 13 ошибка
  • Fatal error c1903 не удается восстановить после предыдущих ошибок остановка компиляции