Ошибка 2 error lnk1120 1 неразрешенных внешних элементов

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.4k29 gold badges111 silver badges186 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,9866 gold badges43 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

31.1k25 gold badges87 silver badges137 bronze badges

answered Sep 23, 2020 at 11:18

Vasantha Ganesh's user avatar

Vasantha GaneshVasantha Ganesh

4,6003 gold badges25 silver badges33 bronze badges

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

ChrisQIUChrisQIU

3062 silver badges6 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

3,1511 gold badge36 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,2211 gold badge24 silver badges23 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

4117 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

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

answered Jul 29, 2022 at 5:34

Fractal Salamander's user avatar

The «Fatal Error LNK1120: 1 unresolved externals» is a common error message in C++ development, indicating that a symbol (typically a function or variable) has been declared but not defined. This can occur for a variety of reasons, including missing library files, incorrect project settings, or errors in the source code. In this article, we will explore several solutions to this issue, including:

Method 1: Verify Library Linkage

If you are facing the C++ Fatal Error LNK1120: 1 unresolved externals error, it means that the linker is unable to find the definition of a function or variable that is declared in one module but defined in another. One way to solve this problem is by using the Verify Library Linkage feature in Visual Studio. Here are the steps to do it:

  1. Open your Visual Studio project and go to the Solution Explorer.

  2. Right-click on the project that is giving you the error and select Properties.

  3. In the Properties window, go to the Configuration Properties > Linker > General section.

  4. Set the Enable Incremental Linking option to No (/INCREMENTAL:NO).

  5. Go to the Configuration Properties > Linker > Input section.

  6. In the Additional Dependencies field, add the name of the library that contains the definition of the missing function or variable.

  7. Go to the Configuration Properties > Linker > Debugging section.

  8. Set the Generate Debug Info option to Yes (/DEBUG).

  9. Build your project.

  10. If the error persists, use the dumpbin tool to verify that the library is being linked correctly. Open a command prompt and navigate to the directory where the library is located. Then, run the following command:

dumpbin /exports <library_name>

This will display a list of all the exported symbols in the library. Make sure that the missing function or variable is included in the list.

  1. If the missing function or variable is not included in the list, it means that the library is not being linked correctly. Check the library path and make sure that it is included in the project properties.

That’s it! By using the Verify Library Linkage feature and the dumpbin tool, you should be able to fix the C++ Fatal Error LNK1120: 1 unresolved externals error. Here are some example codes that might help you understand the process better:

// Header file: mylib.h
#pragma once

int add(int a, int b);

// Source file: mylib.cpp
#include "mylib.h"

int add(int a, int b)
{
    return a + b;
}

// Main file: main.cpp
#include "mylib.h"

int main()
{
    int result = add(3, 4);
    return 0;
}

In this example, the add() function is declared in the mylib.h header file and defined in the mylib.cpp source file. The main.cpp file uses the add() function, but if the mylib.cpp file is not linked correctly, you will get the C++ Fatal Error LNK1120: 1 unresolved externals error. By following the steps outlined above, you should be able to fix this error and successfully build your project.

Method 2: Check Source Code for Missing Definitions

To fix the C++ Fatal Error LNK1120: 1 unresolved externals, you can try checking the source code for missing definitions. Here are the steps you can follow:

  1. Identify the missing definition: The first step is to identify which definition is missing. Look for the function or variable that is causing the error.

  2. Check the source code: Once you have identified the missing definition, check if it is defined in the source code. Look for the function or variable declaration in the header files and the implementation in the source files.

  3. Add the missing definition: If the definition is missing, add it to the source code. Make sure the function or variable is declared in the header file and implemented in the source file.

  4. Rebuild the project: After adding the missing definition, rebuild the project and check if the error has been resolved.

Here is an example of how to check for a missing function definition:

// header file
#ifndef MY_HEADER_FILE_H
#define MY_HEADER_FILE_H

int add(int a, int b);

#endif

// source file
#include "my_header_file.h"

int main() {
    int result = add(1, 2);
    return 0;
}

// implementation file
int add(int a, int b) {
    return a + b;
}

In this example, the add function is declared in the header file and called in the source file. The implementation of the add function is defined in the implementation file. If the implementation file is missing or the function is not implemented correctly, you may get the LNK1120 error.

By checking the source code for missing definitions, you can easily fix the LNK1120 error and ensure that your code compiles correctly.

Method 3: Ensure Correct Project Settings

To fix the C++ Fatal Error LNK1120: 1 unresolved externals, you can ensure correct project settings. Here are the steps to follow:

  1. Open your Visual Studio project and navigate to the Solution Explorer.

  2. Right-click on your project and select Properties.

  3. In the Properties window, navigate to Linker > Input.

  4. In the Additional Dependencies field, add the name of the library that is causing the error. For example, if the error is caused by a missing reference to a function in the math library, you would add «libm.lib» to the list of dependencies.

  5. Click OK to save your changes and close the Properties window.

  6. Rebuild your project by selecting Build > Rebuild Solution from the menu bar.

  7. If the error persists, try adding the library path to your project settings. To do this, navigate to Linker > General in the Properties window and add the path to the library files in the Additional Library Directories field.

  8. Rebuild your project again and the error should be resolved.

Here’s an example of how to add the math library as a dependency:

#include <cmath>

int main()
{
    double x = 2.0;
    double y = std::sin(x);
    return 0;
}

In this example, we’re using the sin function from the math library. To ensure that the function is linked correctly, we need to add the library as a dependency in our project settings.

#include <cmath>

#pragma comment(lib, "libm.lib")

int main()
{
    double x = 2.0;
    double y = std::sin(x);
    return 0;
}

In this updated example, we’ve added the #pragma directive to link the math library. This will ensure that the sin function is resolved correctly at link time.

Method 4: Debugging with the Linker

When you encounter the C++ Fatal Error LNK1120: 1 unresolved externals, it means that the linker cannot find the definition of a symbol that is declared in your code. This error can be frustrating, but it is usually easy to fix. One way to fix this error is by using the «Debugging with the Linker» method. Here are the steps to follow:

Step 1: Identify the unresolved symbol

The first step is to identify the unresolved symbol. Look at the error message to see which symbol is causing the error. For example, if the error message says «unresolved external symbol _main», it means that the linker cannot find the main function.

Step 2: Check the declaration of the symbol

Once you have identified the unresolved symbol, check the declaration of the symbol to make sure it matches the definition. The declaration should be in a header file, and the definition should be in a source file. Make sure that the declaration and definition have the same name, return type, and parameter list.

Step 3: Check the source file for the definition

If the declaration and definition match, check the source file for the definition. Make sure that the definition is not in a different namespace or class than the declaration. Also, make sure that the definition is not commented out or conditionalized out.

Step 4: Check the project settings

If the declaration and definition match and the definition is in the correct source file, check the project settings to make sure that the source file is included in the build. Make sure that the source file is listed in the project settings under «Source Files» or «Compile».

Step 5: Check the library settings

If the declaration and definition match, the definition is in the correct source file, and the source file is included in the build, check the library settings to make sure that the library containing the definition is linked into the project. Make sure that the library is listed in the project settings under «Linker» or «Libraries».

Step 6: Check for name mangling

If the declaration and definition match, the definition is in the correct source file, the source file is included in the build, and the library containing the definition is linked into the project, check for name mangling. C++ compilers often mangle the names of symbols to support overloading. Make sure that the declaration and definition use the same name mangling scheme.

Step 7: Check for C linkage

If the declaration and definition match, the definition is in the correct source file, the source file is included in the build, the library containing the definition is linked into the project, and the name mangling is correct, check for C linkage. If the symbol is declared with C linkage, but the definition is not, the linker will not be able to find the definition. Make sure that the declaration and definition use the same linkage.

Step 8: Check for multiple definitions

If the declaration and definition match, the definition is in the correct source file, the source file is included in the build, the library containing the definition is linked into the project, the name mangling is correct, and the linkage is correct, check for multiple definitions. If the symbol is defined in more than one source file, the linker will not be able to resolve the symbol. Make sure that the symbol is defined in only one source file.

By following these steps, you should be able to fix the C++ Fatal Error LNK1120: 1 unresolved externals with Debugging with the Linker method. Here are some example code snippets to help illustrate the steps:

// Step 1: Identify the unresolved symbol
// Error message: unresolved external symbol _main
// Solution: Add a main function

// Step 2: Check the declaration of the symbol
// Declaration in header file
int main();

// Step 3: Check the source file for the definition
// Definition in source file
int main() {
    return 0;
}

// Step 4: Check the project settings
// Source file listed under "Source Files" or "Compile"

// Step 5: Check the library settings
// Library listed under "Linker" or "Libraries"

// Step 6: Check for name mangling
// Declaration and definition use the same name mangling scheme
extern "C" int _cdecl main();

// Step 7: Check for C linkage
// Declaration and definition use the same linkage
extern "C" int main();

// Step 8: Check for multiple definitions
// Symbol is defined in only one source file

Студворк — интернет-сервис помощи студентам

Программа иллюстрирующая работу бинарных операторов

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
// BitTest - инициируются две переменные и
// выводятся результаты  выполнения 
// операторов ~ , & , | , и ^
#include <cstdio>
#include <cstdlib>
#include <iostream>
using namespace std;
 
int main(int nNumberofArgs, char* pszArgs[])
{
    // установка вывода в шестнадцатеричном виде
    cout.setf(cout.hex);
 
    // инициализация двух аргументов
    int nArg1;
    nArg1 = 0x1234;
 
    int nArg2;
    nArg2 = 0x00ff;
    // выполнение логически операций
    // сначала применяем унарный оператор NOT
    cout << "Arg1              = 0x" << nArg1 << "\n";
    cout << "Arg2              = 0x" << nArg2 << "\n";
    cout << "~nArg1            = 0x" << ~nArg1 << "\n";
    cout << "~nArg2            = 0x" << ~nArg2 << "\n";
 
    // А сейчас бинарные операторы!
    cout << "nArg1 & nArg2 = 0x"
         << (nArg1 & nArg2)
         << "\n";
    cout << "nArg1 | nArg2 = 0x"
         << (nArg1 | nArg2)
         << "\n";
    cout << "nArg1 ^ nArg2 = 0x"
         << (nArg1 ^ nArg2)
         << "\n";
    // ожидание пока пользователь завершит программу
    // для того, чтобы он увидел результаты
    system ("PAUSE");
    return 0;
}

Ошибка
1>MSVCRTD.lib(crtexew.obj) : error LNK2019: ссылка на неразрешенный внешний символ _WinMain@16 в функции ___tmainCRTStartup
1>C:\Users\Федя\Desktop\Study\Битовые_операции\Debug\Битовые_операции.exe : fatal error LNK1120: 1 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

Подскажите, пожалуйста, в чем дело и как исправить?

Usually when I get this error, creating a new project and copy paste the code fix that but now it doesn’t.

Here is the output:

1>------ Build started: Project: myList, Configuration: Debug Win32 ------
1>  List.cpp
1>List.obj : error LNK2019: unresolved external symbol "void __cdecl printStd(struct Student >*)" (?printStd@@YAXPAUStudent@@@Z) referenced in function _main
1>C:\Users\Talmid\Desktop\אמרי\C\myList\Debug\myList.exe : fatal error LNK1120: 1 unresolved >externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

And the code:

#include <stdio.h>
#include <stdlib.h>

#define SUCCESS 1
#define FAILURE 0

// A definition of some information type:
typedef struct
{
char name[20];
int id;
}Student;

// A definition of a single node
typedef struct node_s
{
Student data;
struct node_s *next;
}Node;

// a definition of "list manager":
typedef struct
{
Node *start;
int num;
}List;

List *createList();
int insertToList(List *ptrList, Student *ptrStu);
int removeFirst(List *ptrList, Student *ptrStu);
Node *getRecord(List *ptrList, int recNum);
void printList(List *ptrList);
void printRec(Node *ptrNode);
void printStd(Student *std);
void freeList(List *ptrList);
void shutDown(List *ptrList);

//Creates a new 'list manager', initializes it and returns its value;
List *createList()
{
    List *ptrNewList = (List *)malloc(sizeof(List));
    if(ptrNewList)
    {
        ptrNewList->start = NULL;
        ptrNewList->num = 0;
    }
    return ptrNewList;
}

// free 'list manager'
void shutDown(List *pList)
{
    if(pList != NULL)
        free(pList);
}

// inserts one record a the head of the list
int insertToList(List *ptrList, Student *ptrStu)
{
    Node *ptrNewNode = (Node *)malloc(sizeof(Node));
    if(ptrNewNode)
    {
        ptrNewNode->data = *ptrStu;
        ptrNewNode->next = ptrList->start;
        ptrList->start = ptrNewNode;
        ptrList->num++;
        return SUCCESS;
    }
    return FAILURE;
}

// remooves the first node from the list
int removeFirst(List *ptrList, Student *ptrStu)
{
    Node *ptrDel;
    if(ptrList->start != NULL)
    {
        ptrDel = ptrList->start;
        ptrList->start = ptrDel->next;
        ptrList->num--;
        *ptrStu = ptrDel->data;
        free(ptrDel);
        return SUCCESS;
    }
    return FAILURE;
}

// gets the data of the recNum node
Node *getRecord(List *ptrList, int recNum)
{
    Node *ptrNode;
    int nodeNum = 1;
    ptrNode = ptrList->start;
    while((nodeNum<recNum) && (ptrNode != NULL))
    {
        ptrNode = ptrNode->next;
        nodeNum++;
    }
    return ptrNode;
}

// prints the entire list
void printList(List *ptrList)
{
    Node *ptrNode;
    int i;
    ptrNode = ptrList->start;

    i = 1;
    while(ptrNode != NULL)
    {
        printf("%2d: ",i);
        printRec(ptrNode);
        ptrNode = ptrNode->next;
        i++;
    }
    printf("\n");
}

// prints a given record
void printRec(Node *ptrNode)
{
    printf("name is %10s, id is %d.\n", ptrNode->data.name, ptrNode->data.id);
}

// prints a given student
void printSt(Student *std)
{
    printf("name is %10s, id is %d.\n", std->name, std->id);
}

//free all nodes (dynamic allocation)
void freeList(List *ptrList)
{
        Node *ptrDel;
    if(ptrList != NULL)
    {
        ptrDel = ptrList->start;
        while(ptrDel)
        {
            ptrList->start = ptrDel->next;
            free(ptrDel);
            ptrDel = ptrList->start;
        }
    }
}

void main()
{
    List *l1 = NULL;
    Node *n1 = NULL;
    Student *s1 = NULL;
    int i, status;
    int wantedIndexElement = 3;
    Student studentsArr[] = {
                                {"Rina",134},
                                {"Tomer",22307},
                                {"Rotem",3732},
                                {"Yosef",773},
                                {"Anat",9998},
                                {"Vered",14555},
                                {"Malkishua",878},
                                {"David",6543},
                                {"Yigal",9870},
                                {"Beni",123}
                            };
    int arrLen = sizeof(studentsArr)/sizeof(Student);
    l1 = createList();
    if(l1 == NULL)
    {
        printf("problem to allocate List (list manager)\n");
        exit(1);
    }
    for(i=0;i<arrLen;i++)
    {
        status = insertToList(l1,&studentsArr[i]);
        if(status == FAILURE)
        {
            printf("Failed to insert to the list!!!\n");
            exit(1);
        }
    }
    printList(l1);
    n1 = getRecord(l1,wantedIndexElement);

    if(n1 != NULL)
        printRec(n1);
    else
        printf("No such element %d \n",wantedIndexElement);



    s1 = (Student *)malloc(sizeof(Student));
    if (removeFirst(l1,s1) == FAILURE)
    {
        printf("Failed to remove from list!!!\n");
            exit(1);
    }

    printf("The   student has been deleted:\n");
    printStd(s1);


    freeList(l1);
    shutDown(l1);
    l1 = NULL;
    putchar('\n');
    getchar();
}

Since it’s a long code you don’t really need to check it, there are no mistakes.. even the console said so :D

So what this error means?why do I get it?how can I fix it? it leads me to an exe that doesn’t even exist.

Thanks

Дан код 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:\Users\Daniel\Documents\GitHub\SimpleLang\Debug\SimpleLang.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:\Users\Daniel\Documents\GitHub\SimpleLang\Debug\Tests.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 2 failed, 1 up-to-date, 0 skipped ==========

Понравилась статья? Поделить с друзьями:
  • Ошибка 2 5 ростелеком телевизор
  • Ошибка 2 4 сузуки 300
  • Ошибка 2 10060 герои 3 hota
  • Ошибка 1a55 volvo
  • Ошибка 1a37 epson