Ошибка средств компоновщика lnk1120

Дан код 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 ==========

Reee

21 / 21 / 7

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

Сообщений: 65

1

12.10.2010, 15:02. Показов 46936. Ответов 12

Метки нет (Все метки)


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

Поскажите где ошибка?

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
#include<iostream>
using namespace std;
 
 
int main()
{
    for(;;)
    {
    char* III1="S";
    char* III2="D";
    char* III3="F";
    char* III4="G";
    char* III5="H";
    int a=0;
    cin>>a;
    switch(a)
    {
    case 1 : cout<<III1<<endl;
        break;
    case 2 : cout<<III2<<endl;
        break;
    case 3 : cout<<III3<<endl;
        break;
    case 4 : cout<<III4<<endl;
        break;
    case 5 : cout<<III5<<endl;
        break;
    }
    cout<<"Продолжить?"<<endl;
    char vvod;
    cin>>vvod;
    if(vvod=='y'||vvod=='Y')
        break;
    else
        cout<<"Вы продолжили..."<<endl;
    }
    return 0;
}

1>LINK : error LNK2001: неразрешенный внешний символ «_mainCRTStartup»
1>D:2010 profesional45165Debug45165.exe : fatal error LNK1120: 1 неразрешенных внешних элементов
1>
1>СБОЙ построения.



0



dihlofos

Бродяга

314 / 268 / 56

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

Сообщений: 553

12.10.2010, 15:04

2

Может из-за этого:

C++
1
cout<<"Продолжить?"<<endl;



0



21 / 21 / 7

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

Сообщений: 65

12.10.2010, 15:06

 [ТС]

3

Не… не это.



0



70 / 44 / 9

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

Сообщений: 140

12.10.2010, 15:11

4

В коде грубых ошибок (логика не имеется ввиду=) ) нет, компилируется и даже практически работает. Смотрите в сторону настроек линковщика.



0



asics

Freelance

Эксперт С++

2890 / 1825 / 356

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

Сообщений: 3,841

12.10.2010, 15:43

5

Разве не так надо писать ?

C++
1
char* III1='S';



0



Эксперт С++

5054 / 3115 / 271

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

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

12.10.2010, 15:55

6

Нет, так вы инициализируете указатель символом S, это ошибка. А так указатель будет указывать на строку «S», которая к тому же имеет нуль-терминатор в конце.



0



21 / 21 / 7

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

Сообщений: 65

12.10.2010, 16:41

 [ТС]

7

Цитата
Сообщение от Юрий АЛексеевич
Посмотреть сообщение

В коде грубых ошибок (логика не имеется ввиду=) ) нет, компилируется и даже практически работает. Смотрите в сторону настроек линковщика.

А если я там ничево не трогал?Гдет ниделю назад всё было нормально, а щас вот так.(Тоесть программой ваще не пользовался.)

Добавлено через 30 минут
Что могло сбится в настройках Microsoft Visual Studio 2010?
Так как мой пример норм работает в Microsoft Visual C++ 2008 Express Edition.



0



1562 / 1040 / 94

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

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

12.10.2010, 18:06

8

Какая то lib не подключена, где описывается _mainCRTStartup



0



Freelance

Эксперт С++

2890 / 1825 / 356

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

Сообщений: 3,841

12.10.2010, 18:41

9

Запишы ето /entry:»mainCRTStartup в проектсвойствакомпоновщиккомандная строкадопольнителние опции



1



2 / 2 / 1

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

Сообщений: 10

12.10.2010, 20:48

10

у меня была такая проблема, и дело было вот в чем. Студия (у меня 2010) по умолчанию вместо main юзает _tmain (для конс.прил.) попробуйте создать мастером проэкт, с готовым заголовком, и посмотрите как там называеться мэйн.



0



Freelance

Эксперт С++

2890 / 1825 / 356

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

Сообщений: 3,841

12.10.2010, 20:53

11

Tim0xAA, не только MSVS10 юзает по дефу _tmain,и вопше дело не в етом,в студии можно щитать что main ето синоним слова _tmain.



0



Эксперт JavaЭксперт С++

8381 / 3613 / 419

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

Сообщений: 10,708

13.10.2010, 14:20

12

Clean, а потом Rebuild Solution



0



бжни

2473 / 1684 / 135

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

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

13.10.2010, 16:20

13

в Linker/System/Subsystem должно быть Console (/SUBSYSTEM:CONSOLE) или Not Set



1



title description ms.date f1_keywords helpviewer_keywords ms.assetid

Linker tools error LNK1120

Describes the LNK1120 linker error, which reports the number of unresolved external symbol errors in the link.

10/31/2019

LNK1120

LNK1120

56aa7d36-921f-4daf-b44d-cca0d4fb1b51

Linker tools error LNK1120

number unresolved externals

Error LNK1120 reports the number of unresolved external symbol errors in the current link.

Each unresolved external symbol first gets reported by a LNK2001 or LNK2019 error. The LNK1120 message comes last, and shows the unresolved symbol error count.

[!IMPORTANT]
You don’t need to fix this error. 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.

I was writing a C++ program in visual studio 2013 and the
program is very simple one and when I compile there was error
this is third time I see this error.
Here’s the program:

#include <iostream>
using namespace std;

int main()
{
    int x, y, z = 0;
    char c;
    bool quit = true;

    while (quit == true)
    {
        cout << "enter a number : ";
        cin >> x;
        cout << "enter a sign : ";
        cin >> c;
        cout << "enter another number : ";
        cin >> y;

        if (c == '+')
            z = x + y;
        if (c == '-')
            z = x - y;
        if (c == '*')
            z = x * y;
        if (c == '/' && y != 0)
            z = x / y;
        if (c == 'q')
            quit = false;

        cout << "Answer is : " << z << endl;
    }

    return 0;
}

…and here’s the error:

1>------ Build started: Project: Calculator_madeByMe, Configuration: Debug Win32 ------
1>  Source.cpp
1>MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol _WinMain@16 referenced in function ___tmainCRTStartup
1>C:UsersSorenadocumentsvisual studio 2013ProjectsCalculator_madeByMeDebugCalculator_madeByMe.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========>

Jerry Coffin's user avatar

Jerry Coffin

473k80 gold badges623 silver badges1108 bronze badges

asked May 23, 2014 at 23:13

Sorena's user avatar

2

Your compiling as a Windows application, which does not use the «int main()» signature when calling the entry point.

Switch to a console application in Project -> Properties -> Linker -> System -> SubSystem -> Console. There might be more involved than just this setting, so if it still doesn’t compile, remake your project and make sure to choose Console Application.

answered May 23, 2014 at 23:19

mukunda's user avatar

mukundamukunda

2,90915 silver badges20 bronze badges

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

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

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ФедяDesktopStudyБитовые_операцииDebugБитовые_операции.exe : fatal error LNK1120: 1 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

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

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 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,9666 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

30.5k22 gold badges85 silver badges133 bronze badges

answered Sep 23, 2020 at 11:18

Vasantha Ganesh's user avatar

Vasantha GaneshVasantha Ganesh

4,5423 gold badges25 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

3,1011 gold badge35 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,2111 gold badge24 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

4097 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

ChrisQIUChrisQIU

1861 silver badge6 bronze badges

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

answered Jul 29, 2022 at 5:34

Fractal Salamander's user avatar

I get the ERROR LNK1120: 1 unresolved externals & ERROR LNK2019: unresolved external symbol ! While Compiling

Some threads — I end up while searching — say is something about class definitions and other that is something with the .cpp /.h files

The errors:

ERROR LNK1120: 1 unresolved externals.  

ERROR LNK2019: unresolved external symbol "public: __thiscall bandera_Triang::~bandera_Triang(void)" (??1bandera_Triang@@QAE@XZ) referenced in function _main.

Here is the code:

#include <iostream>
using namespace std;

class bandera_Triang {
private:
    float aSide, bSide, cSide;

public:
    bandera_Triang(){ //Cost. sin Param...
        aSide = 0;
        bSide = 0;
        cSide = 0;
    }
    bandera_Triang(float A, float B, float C){ //Const. con Param...
        aSide = A;
        bSide = B;
        cSide = C;
    }

    //Sets...
    void set_A(float A){ aSide = A; }
    void set_B(float B){ bSide = B; }
    void set_C(float C){ cSide = C; }

    //Gets...
    float get_A(){ return aSide; }
    float get_B(){ return bSide; }
    float get_C(){ return cSide; }

    ~bandera_Triang(); //destructor...



    bool esTriang(){ //Desigualdad Triangular...
        if (aSide < bSide + cSide && bSide < aSide + cSide && cSide < aSide + bSide) {
            return true;
        }
        else
            return false;
    }

    string triangOno(bool esTriang()){ //Print si es o no triangulo...
        if (esTriang() == true){
            return "Es Triangulo.";
        }
        else { return "NO es Triangulo."; }
    }

    string tipoTriang(){
        if (aSide == bSide && bSide == cSide){
            return "El triangulo es Equilatero.";
        }
        else
        if (aSide == bSide || aSide == cSide || bSide == cSide){
            return "El triangulo es Isosceles. ";
        }
        return "El triangulo es Escaleno.";
    }

    float arTriang(float aSide, float bSide, float cSide){ //Area Triangulo con F.Heron.

        float lado_A, lado_B, lado_C, SemiPerim, areaTriang; //Variables locales para calculo.

        SemiPerim = (lado_A + lado_B + lado_C) / 2; //Calculo de Semiperimetro.

        areaTriang = sqrt(SemiPerim * (SemiPerim - lado_A) * (SemiPerim - lado_B) * (SemiPerim - lado_C));

        return areaTriang;
    }

    string printArea(float arTriang){ cout << "El area del Triangulo es: " << arTriang << "cm2." << endl; } //Imprime Area :)
}; //Fin Clase Triangulo


//Inicia Main

int main(){

    bandera_Triang triangA;

    system("pause");
} 

nicael's user avatar

nicael

18.4k13 gold badges57 silver badges90 bronze badges

asked Apr 5, 2015 at 7:12

10110's user avatar

4

There are two steps to creating the executable, compiling and linking. During the compilation phase, you sometimes only make a promise, like «there is a function int foo(float)» even though that function isn’t part of this compilation unit. The compiler will take your word and only insert a placeholder. Later on, the linker will assemble the different parts of your program and resolve that placeholder. Since it doesn’t find the promised function, it errors out.

The promised function is the destructor, which you declared (~bandera_Triang();) but never actually provided. If you didn’t promise to provide one, the compiler would have created this special function for you, so I’d suggest you just remove the declaration. In order to let the teacher know you considered this, you can write it like this:

// default dtor is fine
// ~bandera_Triang();

or you could implement it with an empty body.

answered Apr 5, 2015 at 7:26

Ulrich Eckhardt's user avatar

Ulrich EckhardtUlrich Eckhardt

16.5k3 gold badges28 silver badges54 bronze badges

2

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

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ФедяDesktopStudyБитовые_операцииDeb ugБитовые_операции.exe : fatal error LNK1120: 1 неразрешенных внешних элементов
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

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

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

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,3803 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

3817 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

Я получаю эти две ошибки, и я не могу найти решение, которое работает.

LNK1120: 1 неразрешенное внешнее

Ошибка 1 ошибка LNK2019: неразрешенный внешний символ «public: __thiscall Vector3D :: Vector3D (класс Vector3D const &) «(?? 0Vector3D @@ QAE @ ABV0 @@ Z) ссылка на функцию» public: класс Vector3D __thiscall Vertex :: GetPosition (void) «(? GetPosition @ Vertex @@ QAE? AVVector3D @@ XZ)

Я думаю, что это связано с моим оператором Matrix и конструктором в моем классе Vector 3d
Любая помощь будет высоко ценится, так как я новичок в C ++

#ifndef MATRIX4_H
#define MATRIX4_H

#include "Vector3D.h"
class Matrix4
{
public:
Matrix4();
Matrix4(const Matrix4& rhs);
~Matrix4();

Vector3D Matrix4::operator *(Vector3D vector)
{
Vector3D newVector;

newVector.SetVector_X((m[0][0] * vector.GetVector_X()) + (m[0][1] * vector.GetVector_Y()) + (m[0][2] * vector.GetVector_Z()) + m[0][3]);
newVector.SetVector_Y((m[0][0] * vector.GetVector_X()) + (m[1][1] * vector.GetVector_Y()) + (m[1][2] * vector.GetVector_Z()) + m[1][3]);
newVector.SetVector_Z((m[0][0] * vector.GetVector_X()) + (m[2][1] * vector.GetVector_Y()) + (m[2][2] * vector.GetVector_Z()) + m[2][3]);
return Vector3D(newVector.GetVector_X(),newVector.GetVector_Y(),newVector.GetVector_Z());

}

void SetMatrix(float matrix[4][4])
{
memcpy(m,matrix,sizeof(matrix));
}

private:
float m[4][4];
};
#endif

Файл Vector3D.h

#ifndef VECTOR3D_H
#define VECTOR3D_H

class Vector3D
{
public:
Vector3D();
Vector3D(const Vector3D& rhs);
~Vector3D();

Vector3D(float VectorX, float VectorY, float VectorZ)
{
x=VectorX;
y=VectorY;
z=VectorZ;
}

void SetVector3D(float vector_X, float vector_Y, float vector_Z)
{
x = vector_X;
y = vector_Y;
z = vector_Z;
}

void SetVector_X(float vector_X)
{
x=vector_X;
}

void SetVector_Y(float vector_Y)
{
y=vector_Y;
}

void SetVector_Z(float vector_Z)
{
z=vector_Z;
}

float GetVector_X()
{
return x;
}

float GetVector_Y()
{
return y;
}

float GetVector_Z()
{
return z;
}

Vector3D GetVector()
{
return Vector3D(x,y,z);
}

private:
float x;
float y;
float z;

};
#endif

1

Решение

Это говорит о том, что компоновщик не может найти реализацию Vector3D(const Vector3D& rhs);, Этот конструктор объявлен в вашем векторном классе, но не определен.

У вас есть реализация конструктора где-то в .cpp файл, а этот файл известен вашему компилятору?

Компиляция C / C ++ работает так: сначала у вас есть несколько так называемых «модулей компиляции» — обычно каждый .cpp-file является одним из таких модулей компиляции. Ваша программа состоит из всех этих отдельных модулей, связанных друг с другом (процесс «связывания» происходит после компиляции). Каждая функция, которая вызывается где-то, должна быть определена ровно один раз в некотором модуле компиляции, если он не определен встроенным (как другие методы вашего класса). Если метод объявлен, но не определен, компилятор не будет жаловаться — только компоновщик. Представьте себе блоки компиляции, имеющие «розетки» и «соединители», которые соответствуют соответствующим «розеткам» других блоков. Процесс компиляции просто создает эти модули, принимая определенную форму «сокета» (как указано в объявлениях), тогда как компоновщик фактически пытается соединить каждый «сокет» с его «соединителем». Итак, вы видите, как процесс компиляции может быть успешным, но ссылки нет.

Ошибки компоновщика могут быть сложно решить, особенно если вы еще не так опытны. Там может быть много причин для них:

  • Отсутствует реализация / определение
  • Определение существует, но почему-то не компилируется (потому что файл не передается компилятору и т. Д.)
  • Различные версии библиотек и т. Д.

И многое другое ..

Редактировать: Кроме того, вы должны передать вектор по константной ссылке и создать newVector, вызвав его конструктор, вместо создания объекта по умолчанию и последующего присвоения. И окончательное строительство в return statement тоже не нужен. Улучшенный код:

Vector3D Matrix4::operator *(const Vector3D& vector)
{
return Vector3D(
(m[0][0] * vector.GetVector_X()) + (m[0][1] * vector.GetVector_Y()) + (m[0][2] * vector.GetVector_Z()) + m[0][3],
(m[0][0] * vector.GetVector_X()) + (m[1][1] * vector.GetVector_Y()) + (m[1][2] * vector.GetVector_Z()) + m[1][3],
(m[0][0] * vector.GetVector_X()) + (m[2][1] * vector.GetVector_Y()) + (m[2][2] * vector.GetVector_Z()) + m[2][3]
);
}

5

Другие решения

Ваша реализация Vector3D кажется, что отсутствует фактическая реализация для конструктора копирования, следовательно, неразрешенная внешняя ошибка. Если вы не собираетесь копировать объект Vector3D, вы не сможете передать его в Matrix::operator* по значению, что бы вызвать копию.

Тем не менее, я не думаю, что есть какие-либо причины объявлять и реализовывать конструктор копирования для Vector3D в любом случае, поскольку он содержит только POD-типы, и сгенерированный компилятором конструктор копирования будет работать нормально. То же самое относится и к деструктору, ресурсы для управления отсутствуют, поэтому пусть компилятор выполняет свою работу.

2

Вы реализовали Vector3D конструктор по умолчанию, конструктор копирования и деструктор? Вы показали свои заголовки, но не файлы реализации. Линкер жалуется на отсутствие определения Vector3D::Vector3D(Vector3D const&),

1

  • Remove From My Forums
  • Question

  • Hi, I am building a dll & in the the DllMain() function i am trying to instantiate a class. The dll builds and runs fine (from client programs) when built through Visual Studio IDE.

    But surprisingly, i get a linker error when i build the same through cmd line options ..( & using .mak file)

    following is the error message:-

    dllmain.obj : error LNK2001: unresolved external symbol «public: __thiscall IfxLashmDllMgrDbg::IfxLashmDllM
    grDbg(struct HINSTANCE__ *)» (??0IfxLashmDllMgrDbg@@QAE@PAUHINSTANCE__@@@Z)
    .bin/Releaselashm.dll : fatal error LNK1120: 1 unresolved externals
    NMAKE : fatal error U1077: ‘link.exe’ : return code ‘0x460’
    Stop.
    error: nmake lashm failed

    Here is dllmain code fragment:-

    //——
    BOOL APIENTRY
    DllMain( HINSTANCE hDll
        , DWORD fdwReason
        , LPVOID lpvReserved )
    //——
    {
     switch ( fdwReason )
     {
      case DLL_PROCESS_ATTACH:
      //———————-
      {
    #if IFX_LASHMDLL_TRACE_IF==1
       if ( !IfxLashmDllMgrDbg::createInstance( hDll ) )
    #else
       if ( !IfxLashmDllMgr::createInstance( hDll ) )
    #endif
       {
        return FALSE;
       }

         }}

    Any help would be much appreciated. Thank you !

Answers

  • Well, unresolved externals are always down to the linker not being able to find something. In this case it is the class member IfxLashmDllMgrDbg::createInstance. Since it builds from the inside the IDE then this is really just a simple case of you forgetting to give the linker something.

    Is IfxLashmDllMgrDbg and IfxLashmDllMgr actually written by you and part of the project or is it a third party library. If it is part of your project then look at your source and object lists to make sure you are compiling the source file and actually passing the object to the linker as linker input. If it is part of a third party library then look at the linker libraries to make sure it is getting linked to the project.

    One thing which has caught my eye that made me wonder, is IfxLashmDllMgrDbg part of the release build of the project? The error message is saying that it can’t find createInstance from IfxLashmDllMgrDbg, I know this is your build and everything, but are you actually trying to use the Dbg version of this in the release build for a reason? If not maybe you should check the compiler command line to see if IFX_LASHMDLL_TRACE_IF has been defined as 1?


    Visit my (not very good) blog at http://c2kblog.blogspot.com/

    • Marked as answer by

      Monday, April 19, 2010 9:34 AM

  • Remove From My Forums
  • Question

  • Hi, I am building a dll & in the the DllMain() function i am trying to instantiate a class. The dll builds and runs fine (from client programs) when built through Visual Studio IDE.

    But surprisingly, i get a linker error when i build the same through cmd line options ..( & using .mak file)

    following is the error message:-

    dllmain.obj : error LNK2001: unresolved external symbol «public: __thiscall IfxLashmDllMgrDbg::IfxLashmDllM
    grDbg(struct HINSTANCE__ *)» (??0IfxLashmDllMgrDbg@@QAE@PAUHINSTANCE__@@@Z)
    .bin/Releaselashm.dll : fatal error LNK1120: 1 unresolved externals
    NMAKE : fatal error U1077: ‘link.exe’ : return code ‘0x460’
    Stop.
    error: nmake lashm failed

    Here is dllmain code fragment:-

    //——
    BOOL APIENTRY
    DllMain( HINSTANCE hDll
        , DWORD fdwReason
        , LPVOID lpvReserved )
    //——
    {
     switch ( fdwReason )
     {
      case DLL_PROCESS_ATTACH:
      //———————-
      {
    #if IFX_LASHMDLL_TRACE_IF==1
       if ( !IfxLashmDllMgrDbg::createInstance( hDll ) )
    #else
       if ( !IfxLashmDllMgr::createInstance( hDll ) )
    #endif
       {
        return FALSE;
       }

         }}

    Any help would be much appreciated. Thank you !

Answers

  • Well, unresolved externals are always down to the linker not being able to find something. In this case it is the class member IfxLashmDllMgrDbg::createInstance. Since it builds from the inside the IDE then this is really just a simple case of you forgetting to give the linker something.

    Is IfxLashmDllMgrDbg and IfxLashmDllMgr actually written by you and part of the project or is it a third party library. If it is part of your project then look at your source and object lists to make sure you are compiling the source file and actually passing the object to the linker as linker input. If it is part of a third party library then look at the linker libraries to make sure it is getting linked to the project.

    One thing which has caught my eye that made me wonder, is IfxLashmDllMgrDbg part of the release build of the project? The error message is saying that it can’t find createInstance from IfxLashmDllMgrDbg, I know this is your build and everything, but are you actually trying to use the Dbg version of this in the release build for a reason? If not maybe you should check the compiler command line to see if IFX_LASHMDLL_TRACE_IF has been defined as 1?


    Visit my (not very good) blog at http://c2kblog.blogspot.com/

    • Marked as answer by

      Monday, April 19, 2010 9:34 AM

На чтение 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

  • Remove From My Forums
  • Вопрос

  • пытаюсь создать DLL, два файла MyLib.cpp

    void __fastcall Delete(void *param)
    {}

    и файл main.def с содержимым

    LIBRARY MyLib
    EXPORTS
    Delete;

    При компиляции с параметром /MD никаких ошибок не возникает.

    При компиляции с параметром /MT выдает ошибки:

    Ошибка 4
    error LNK2001: неразрешенный внешний символ «Delete»
    Ошибка 5
    error LNK1120: неразрешенных внешних элементов: 1

    При этом, если изменить Delete на Delete2, никаких ошибок не возникает.

    как это исправить?

Ответы

  • Экспорт идентификаторов из DLL может быть выполнен двумя способами: через файл определения модуля (DEF) и модификаторами __declspec(dllexport). Второй способ более гибкий, т.к. имя функции «декорируется»,
    т.е. добавляется информация о классе, пространстве имен и проч. Однако затрудняет явный поиск имени в разделе экспорта (т.к. только компилятор знает, какое имя в результате получится).

    При использовании DEF-файла в раздел экспорта попадает лишь имя функции (без искажений), поэтому такое имя должно быть уникальным по всей DLL.

    Можно сделать так: уберите из проекта DEF-файл, а определение функции перепишите в таком виде:

    extern "C" __declspec(dllexport) void Delete(void *param)
    {
    }

    Т.е. функция должна вызываться по соглашению __cdecl, а extern «C» выключит декорирование ее имени.


    Если сообщение помогло Вам, пожалуйста, не забудьте отметить его как ответ данной темы. Удачи в программировании!

    • Помечено в качестве ответа

      15 февраля 2015 г. 17:05

Здравствуйте. Я новичок в c++, недавно окончил наследование и решил перейти к изучению графической библиотеки SDL. Я установил последнюю версию библиотеки, подключил ее к проекту, но на этапе сборки проекта возникает ошибка (причем не в самом коде, а в проекте).
мой код:
#include

using namespace std;

int main()
{
if (SDL_Init(SDL_INIT_AUDIO | SDL_INIT_VIDEO))
{
exit(1);
}
}

Текст ошибки :
1>MSVCRTD.lib(exe_winmain.obj) : error LNK2019: ссылка на неразрешенный внешний символ _WinMain@16 в функции «int __cdecl invoke_main(void)» (?invoke_main@@YAHXZ).
1>C:UsersUsersourcereposProject10DebugProject10.exe : fatal error LNK1120: неразрешенных внешних элементов: 1
1>Сборка проекта «Project10.vcxproj» завершена с ошибкой.
Скриншот ошибки :
6113dc00a2ee5883953270.png

  • Ошибка средней величины m мера отличия выборки от
  • Ошибка средней арифметической формула excel
  • Ошибка средней арифметической стандартная ошибка разницы показателей
  • Ошибка средней арифметической выборки
  • Ошибка средней арифметической величины показывает тест