Link error lnk2001 unresolved external symbol maincrtstartup

I'm a newbie working through Horton's Beginning Visual C++.  I've been at it for several months.  Last week I got two (related?) errors resuting in a failure to build.
  • Remove From My Forums
  • Question

  • I’m a newbie working through Horton’s Beginning Visual C++.  I’ve been at it for several months.  Last week I got two (related?) errors resuting in a failure to build.

    Horton has us setting Project Properties General Characterset to «Not Set».  We start off with Win32 Console empty project with Precompiled headers.  It has worked fine for months until last week.  I can’t even build a «hello world» 1
    line project in VC++ 2010, now.

    I’ve tried two things I found in the forums:

     1.  Set Character Set to Unicode.  (this eliminates the AlwaysCreate is true error but not the fatal LNK2001→LNK1120 error.  Just to repeat, up until last week this was NOT giving me any problems.

    2.  I also tried adding a manifest validate line to the manifest command line.  No joy.

    Finally, this morning I downloaded and reinstalled Visual Studio in hopes that that would work.  Nope.

    I would appreciate anyone’s ideas on how to solve this.  Win 7 (64bit) Visual Studio 2010 Ver 10.0.30319.1

    1>—— Build started: Project: Test2, Configuration: Debug Win32 ——

    1>Build started 3/13/2011 6:02:05 PM.

    1>InitializeBuildStatus:

    1> Touching «DebugTest2.unsuccessfulbuild».

    1>ManifestResourceCompile:

    1> All outputs are up-to-date.

    1>LINK : error LNK2001: unresolved external symbol _mainCRTStartup

    1>c:usersdaviddocumentsvisual studio 2010ProjectsTest2DebugTest2.exe : fatal error LNK1120: 1 unresolved externals

    1>

    1>Build FAILED.

    • Moved by

      Monday, March 14, 2011 8:46 AM
      move to VC++ forum for better support. (From:Visual Studio Debugger)

Answers

  • Hi,

    According to your description, I think you have a issue about build your C++ project.

    Could you please follow these steps.

    1. Click File menu and choose the Add->project.

    2. Expand the Visual C++ node, select Win32, and click Win32 Console Application (please make sure that you click this option).

    3. Input the name and click on OK.

    4. Make sure that Application type is Console Application , do not change anything, and select Finish.

    5. There is a _tmain function in the cpp file which has the same name with the project.

    6. Build and Start your project or Click F5.

    If your project cannot build or run successfully, please check your configurations of Visual Studio.

    On the other hand  I have followed your steps in my Visual Studio 2010. However it built successfully.  Here is my project and files.

    http://cid-ae2442667686801e.office.live.com/self.aspx/.Documents/T1.rar

    Could you build and run the project in your Visual Studio? If it cannot , maybe there are some  configuration issues in your computer or Visual Studio. 
    Please try to reinstall your windows or Visual Studio. If they still have issue , feel free and let me know.

    Best Regards,

    Rob


    Rob Pan [MSFT]
    MSDN Community Support | Feedback to us
    Get or Request Code Sample from Microsoft
    Please remember to mark the replies as answers if they help and unmark them if they provide no help.

    • Marked as answer by
      Rob Pan
      Monday, March 21, 2011 2:31 AM

description title ms.date f1_keywords helpviewer_keywords ms.assetid

Learn more about: Linker Tools Error LNK2001

Linker Tools Error LNK2001

10/22/2021

LNK2001

LNK2001

dc1cf267-c984-486c-abd2-fd07c799f7ef

unresolved external symbol «symbol«

The compiled code makes a reference or call to symbol. The symbol isn’t defined in any libraries or object files searched by the linker.

This error message is followed by fatal error LNK1120. To fix error LNK1120, first fix all LNK2001 and LNK2019 errors.

There are many ways to get LNK2001 errors. All of them involve a reference to a function or variable that the linker can’t resolve, or find a definition for. The compiler can identify when your code doesn’t declare a symbol, but not when it doesn’t define one. That’s because the definition may be in a different source file or library. If your code refers to a symbol, but it’s never defined, the linker generates an error.

What is an unresolved external symbol?

A symbol is the internal name for a function or global variable. It’s the form of the name used or defined in a compiled object file or library. A global variable is defined in the object file where storage is allocated for it. A function is defined in the object file where the compiled code for the function body is placed. An external symbol is one referenced in one object file, but defined in a different library or object file. An exported symbol is one that’s made publicly available by the object file or library that defines it.

To create an application or DLL, every symbol used must have a definition. The linker must resolve, or find the matching definition for, every external symbol referenced by each object file. The linker generates an error when it can’t resolve an external symbol. It means the linker couldn’t find a matching exported symbol definition in any of the linked files.

Compilation and link issues

This error can occur:

  • When the project is missing a reference to a library (.LIB) or object (.OBJ) file. To fix this issue, add a reference to the required library or object file to your project. For more information, see lib Files as linker input.

  • When the project has a reference to a library (.LIB) or object (.OBJ) file that in turn requires symbols from another library. It may happen even if you don’t call functions that cause the dependency. To fix this issue, add a reference to the other library to your project. For more information, see Understanding the classical model for linking: Taking symbols along for the ride.

  • If you use the /NODEFAULTLIB or /Zl options. When you specify these options, libraries that contain required code aren’t linked into the project unless you’ve explicitly included them. To fix this issue, explicitly include all the libraries you use on the link command line. If you see many missing CRT or Standard Library function names when you use these options, explicitly include the CRT and Standard Library DLLs or library files in the link.

  • If you compile using the /clr option. There may be a missing reference to .cctor. For more information on how to fix this issue, see Initialization of mixed assemblies.

  • If you link to the release mode libraries when building a debug version of an application. Similarly, if you use options /MTd or /MDd or define _DEBUG and then link to the release libraries, you should expect many potential unresolved externals, among other problems. Linking a release mode build with the debug libraries also causes similar problems. To fix this issue, make sure you use the debug libraries in your debug builds, and retail libraries in your retail builds.

  • If your code refers to a symbol from one library version, but you link a different version of the library. Generally, you can’t mix object files or libraries that are built for different versions of the compiler. The libraries that ship in one version may contain symbols that can’t be found in the libraries included with other versions. To fix this issue, build all the object files and libraries with the same version of the compiler before linking them together. For more information, see C++ binary compatibility between Visual Studio versions.

  • If library paths are out of date. The Tools > Options > Projects > VC++ Directories dialog, under the Library files selection, allows you to change the library search order. The Linker folder in the project’s Property Pages dialog box may also contain paths that could be out of date.

  • When a new Windows SDK is installed (perhaps to a different location). The library search order must be updated to point to the new location. Normally, you should put the path to new SDK include and lib directories in front of the default Visual C++ location. Also, a project containing embedded paths may still point to old paths that are valid, but out of date. Update the paths for new functionality added by the new version that’s installed to a different location.

  • If you build at the command line, and have created your own environment variables. Verify that the paths to tools, libraries, and header files go to a consistent version. For more information, see Use the MSVC toolset from the command line.

Coding issues

This error can be caused by:

  • Mismatched case in your source code or module-definition (.def) file. For example, if you name a variable var1 in one C++ source file and try to access it as VAR1 in another, this error is generated. To fix this issue, use consistently spelled and cased names.

  • A project that uses function inlining. It can occur when you define the functions as inline in a source file, rather than in a header file. Inlined functions can’t be seen outside the source file that defines them. To fix this issue, define the inlined functions in the headers where they’re declared.

  • Calling a C function from a C++ program without using an extern "C" declaration for the C function. The compiler uses different internal symbol naming conventions for C and C++ code. The internal symbol name is what the linker looks for when resolving symbols. To fix this issue, use an extern "C" wrapper around all declarations of C functions used in your C++ code, which causes the compiler to use the C internal naming convention for those symbols. Compiler options /Tp and /Tc cause the compiler to compile files as C++ or C, respectively, no matter what the filename extension is. These options can cause internal function names different from what you expect.

  • An attempt to reference functions or data that don’t have external linkage. In C++, inline functions and const data have internal linkage unless explicitly specified as extern. To fix this issue, use explicit extern declarations on symbols referred to outside the defining source file.

  • A missing function body or variable definition. This error is common when you declare, but don’t define, variables, functions, or classes in your code. The compiler only needs a function prototype or extern variable declaration to generate an object file without error, but the linker can’t resolve a call to the function or a reference to the variable because there’s no function code or variable space reserved. To fix this issue, make sure to define every referenced function and variable in a source file or library you link.

  • A function call that uses return and parameter types or calling conventions that don’t match the ones in the function definition. In C++ object files, Name decoration encodes the calling convention, class or namespace scope, and return and parameter types of a function. The encoded string becomes part of the final decorated function name. This name is used by the linker to resolve, or match, calls to the function from other object files. To fix this issue, make sure the function declaration, definition, and calls all use the same scopes, types, and calling conventions.

  • C++ code you call, when you include a function prototype in a class definition, but don’t include the implementation of the function. To fix this issue, be sure to provide a definition for all class members you call.

  • An attempt to call a pure virtual function from an abstract base class. A pure virtual function has no base class implementation. To fix this issue, make sure all called virtual functions are implemented.

  • Trying to use a variable declared within a function (a local variable) outside the scope of that function. To fix this issue, remove the reference to the variable that isn’t in scope, or move the variable to a higher scope.

  • When you build a Release version of an ATL project, producing a message that CRT startup code is required. To fix this issue, do one of the following,

    • Remove _ATL_MIN_CRT from the list of preprocessor defines to allow CRT startup code to be included. For more information, see General property page (Project).

    • If possible, remove calls to CRT functions that require CRT startup code. Instead, use their Win32 equivalents. For example, use lstrcmp instead of strcmp. Known functions that require CRT startup code are some of the string and floating point functions.

Consistency issues

There’s currently no standard for C++ name decoration between compiler vendors, or even between different versions of the same compiler. Object files compiled with different compilers may not use the same naming scheme. Linking them can cause error LNK2001.

Mixing inline and non-inline compile options on different modules can cause LNK2001. If a C++ library is created with function inlining turned on (/Ob1 or /Ob2) but the corresponding header file describing the functions has inlining turned off (no inline keyword), this error occurs. To fix this issue, define the functions inline in the header file you include in other source files.

If you use the #pragma inline_depth compiler directive, make sure you’ve set a value of 2 or greater, and make sure you also use the /Ob1 or /Ob2 compiler option.

This error can occur if you omit the LINK option /NOENTRY when you create a resource-only DLL. To fix this issue, add the /NOENTRY option to the link command.

This error can occur if you use incorrect /SUBSYSTEM or /ENTRY settings in your project. For example, if you write a console application and specify /SUBSYSTEM:WINDOWS, an unresolved external error is generated for WinMain. To fix this issue, make sure you match the options to the project type. For more information on these options and entry points, see the /SUBSYSTEM and /ENTRY linker options.

Exported .def file symbol issues

This error occurs when an export listed in a .def file isn’t found. It could be because the export doesn’t exist, is spelled incorrectly, or uses C++ decorated names. A .def file doesn’t take decorated names. To fix this issue, remove unneeded exports, and use extern "C" declarations for exported symbols.

Use the decorated name to find the error

The C++ compiler and linker use Name Decoration, also known as name-mangling. Name decoration encodes extra information about the type of a variable in its symbol name. The symbol name for a function encodes its return type, parameter types, scope, and calling convention. This decorated name is the symbol name the linker searches for to resolve external symbols.

A link error can result if the declaration of a function or variable doesn’t exactly match the definition of the function or variable. That’s because any difference becomes part of the symbol name to match. The error can happen even if the same header file is used in both the calling code and the defining code. One way it may occur is if you compile the source files by using different compiler flags. For example, if your code is compiled to use the __vectorcall calling convention, but you link to a library that expects clients to call it using the default __cdecl or __fastcall calling convention. In this case, the symbols don’t match because the calling conventions are different.

To help you find the cause, the error message shows you two versions of the name. It displays both the «friendly name,» the name used in source code, and the decorated name (in parentheses). You don’t need to know how to interpret the decorated name. You can still search for and compare it with other decorated names. Command-line tools can help to find and compare the expected symbol name and the actual symbol name:

  • The /EXPORTS and /SYMBOLS options of the DUMPBIN command-line tool are useful here. They can help you discover which symbols are defined in your .dll and object or library files. You can use the symbols list to verify that the exported decorated names match the decorated names the linker searches for.

  • In some cases, the linker can only report the decorated name for a symbol. You can use the UNDNAME command-line tool to get the undecorated form of a decorated name.

Additional resources

For more information, see the Stack Overflow question «What is an undefined reference/unresolved external symbol error and how do I fix it?».

SpartakusMd

22 / 22 / 9

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

Сообщений: 173

1

29.01.2011, 21:23. Показов 11308. Ответов 4

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


Здраствуйте.
При отладке кода в MS VS 2010 выдаёт ошибку, но в онлайн компилятор всё работает. Ошибка:
LINK : error LNK2001: неразрешенный внешний символ «_mainCRTStartup»
… : fatal error LNK1120: 1 неразрешенных внешних элементов

После кода есть полный вывод.

Вот страница на ideone.com.
Вот код:

C++
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
#include <iostream>
#include <cstdlib>
#include <stdexcept>
#include <sstream>
#include <iomanip>
 
/**
* Convert the string received as paramater to a number (of type T)
* @param user_input The string to be converted
* @return The converted number
* @throw std::invalid_argument if the conversion couldn't be done
*/
template <typename T>
T string_to_number(const std::string& user_input) throw (std::invalid_argument)
{
   T user_number;
   std::stringstream user_stream(user_input);
   if (user_stream >> user_number)
      return user_number;
   else
      throw(std::invalid_argument(user_input));
}
 
/**
* Populate a square array with elements of type T
* @param arr The array to be populated
* @param dim The dimension or the array (number of lines equals number of columns)
*/
template <typename T>
void populate_array(T* arr, size_t dim) throw (std::invalid_argument)
{
   std::string user_input;
   
   for (size_t i = 0; i < dim; i++)
   {
      for (size_t j = 0; j < dim; j++)
      {
         std::cout << "arr[" << i << "]" << "[" << j << "]" << " = ";
         std::cin >> user_input;
         arr[i + dim * j] = string_to_number<T>(user_input);
      }
   }
}
 
/**
* Display the contents of a square array holding elements of type T
* @param arr The array to be populated
* @param dim The dimension or the array (number of lines equals number of columns)
*/
template <typename T>
void display_array(const T* arr, size_t dim)
{
   for (size_t i = 0; i < dim; i++)
   {
      for (size_t j = 0; j < dim; j++)
      {
         std::cout << std::setw(10) << arr[i + dim * j] << " ";
      }
      std::cout << std::endl;
   }
}
 
/**
* Calculate the sum of the elements on the principa diagonal
* @param arr The array to be populated
* @param dim The dimension or the array (number of lines equals number of columns)
* @return The sum of the elements on the principal diagonal
*/
template <typename T>
T principal_diag_sum(const T* arr, size_t dim)
{
   T sum = 0;
   for (size_t i = 0; i < dim; i++)
      sum += arr[i + dim * i];
   return sum;
}
 
/**
* Calculate the sum of the elements on the secondary diagonal
* @param arr The array to be populated
* @param dim The dimension or the array (number of lines equals number of columns)
* @return The sum of the elements on the secondary diagonal
*/
template <typename T>
T secondary_diag_sum(const T* arr, size_t dim)
{
   T sum = 0;
   for (size_t i = 0; i < dim; i++)
      sum += arr[i + dim * (dim - 1 - i)];
   return sum;
}
 
int main()
{
   int* arr = 0;
   size_t dim;
   std::string user_input;
   std::cout << "Enter the matrix dimension:  ";
   std::cin >> user_input;
   
   try
   {
      dim = string_to_number<int>(user_input);
      arr = new int[dim * dim];
      std::cout << "Enter the array elements" << std::endl;
      
      populate_array<int>(arr, dim);
      display_array<int>(arr, dim);
      
      std::cout << "Sum of elements on the first diagonal is: " << principal_diag_sum<int>(arr, dim) << std::endl;
      std::cout << "Sum of elements on the secondary diagonal is: " << secondary_diag_sum<int>(arr, dim) << std::endl;
   }
   catch(std::invalid_argument& ex)
   {
      std::cout << "Invalid number or outside range: " << ex.what() << std::endl;
      if (arr)
         delete [] arr;
      return EXIT_FAILURE;
   }
   catch(std::bad_alloc& ex)
   {
      std::cerr << "Memory allocation error: " << ex.what() << std::endl;
      return EXIT_FAILURE;
   }
   delete [] arr;
   return EXIT_SUCCESS;
}

Вот вывод:

—— Построение начато: проект: Matrice, Конфигурация: Debug Win32 ——
Построение начато 29.01.2011 19:40:36.
InitializeBuildStatus:
Обращение к «DebugMatrice.unsuccessfulbuild».
ManifestResourceCompile:
Для всех выходных данных обновления не требуется.
LINK : error LNK2001: неразрешенный внешний символ «_mainCRTStartup»
c:documents and settingsadminмои документыvisual studio 2010ProjectsMatriceDebugMatrice.exe : fatal error LNK1120: 1 неразрешенных внешних элементов

СБОЙ построения.

Затраченное время: 00:00:01.29
========== Построение: успешно: 0, с ошибками: 1, без изменений: 0, пропущено: 0 ==========

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



0



Тиран

17.11.2012, 22:50

2

вот у меня та же самая байда , главное дело юзал VC 6 98 года ) все нормально . установил 2010 — тот же код- выдает такую ошибку , что делать подскажите?

574 / 557 / 47

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

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

17.11.2012, 23:04

3

SpartakusMd, какой проект выбрали в студии?
Выбирайте пустой консольный проект и вставляйте туда свой код



0



Тиран

17.11.2012, 23:33

4

почему , когда я создаю пустой консольный вин32 и пишу туда самое -простое :

#include <iostream>

int main () {}

выдает ошибку 1>LINK : error LNK2001: неразрешенный внешний символ «_mainCRTStartup» ((((

а стоит создать заголовочный проект вин32 , программа туда добавляет

#include «stdafx.h» и после этого все работает нормально .

Кто может обьяснить ?

До сегодняшнего дня ,я пробывал использовать VC 6.00 1998 года , так там все было норм — все примеры из книжки перепечатывались и работали ) а тут поставил 2010 и ппц. ничего не компилится, пока не включил STDAFX.h

574 / 557 / 47

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

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

17.11.2012, 23:37

5

А потому что не надо создавать win32 console project
Я же написал, надо создавать пустой проект (empty project)



0



// preprocessor directives—-
#include <iostream> // for program input & output
#include <string> // for string class data
#include <iomanip> // for formatting output
using namespace std;

/* Function: main() *************************************************
*
* application entry point
*/
int main()
{

/* declarations ***********************************************
declare program data
*/
string name; // contributor’s name
int targetContribution; // target contribution amount to the dollar
int actualContribution; // actual contribution amount made to the dollar
int difference; // calculated difference of the target and actual contributions

/* statements *************************************************
code program instructions: will ask for contribution target and actual amount. Will take the
difference of the target and actual amount and display it.
*/

//
// display program headings
//
cout << «Project/program name:U01_BelowTargetReport» << endl;
cout << «by» << endl;
cout << «Joe Blough» << endl;

// enter program loop (do while)
do
{

//
// Step #1: input
//
cout << «Enter Contributors name: «; //ask for contributor’s name
cin >> name;

cout << «Enter target contribution: «; //ask for target contribution
cin >> targetContribution;

cout << «Enter actual contribution: «; //ask for actual contribution
cin >> actualContribution;

//
// Step #2: processing
//
difference = targetContribution — actualContribution; // calculate the difference between actual contribution
// and assign the number to difference

//
// Step #3: output
//

// display the report column headings
// format & print column heading row

cout << «Name Target Actual Difference» << endl;
cout << «—————————-» << endl;

// display the report detail line
// 1 — format & display user name
cout << left; // justification
cout << setw(10); // width for column data
cout << name; // name of contributor

// 2 — format & display target contribution
cout << right; // justification
cout << setw(6); // width for column data
cout << targetContribution; // target contribution amount

// 3 — format & display actual contribution
cout << right; // justification
cout << setw(10); // width for column data
cout << actualContribution; // target contribution amount

// 4 — format & display difference
// note: positive number means target met
cout << right; // justification
cout << setw(14); // width for column data
cout << difference; // target contribution amount

// see if the user wants to continue or to exit the program

cout << «More contributions to process? (y/n): «;
cin >> choice;

cout << endl << «………………………» << endl;

// end of program loop;
// perform application until choice isn’t equal to «y» or «Y»
} while (choice == «y» || choice == «Y»);

//
// program termination
//
// main() program termination (required in all programs)
cin.ignore();
cin.get();

return 0;
}

error message: Error 1 error LNK2001: unresolved external symbol _mainCRTStartup J:rvc 276CIS27627602_IntroToCPPU01_BelowProjectReportLINK

that’s usually because you choose the wrong project type.
So you need to create a new project where you need to make sure that it is actually a console project

You don’t really need to start a new project. Just go to project settings, linker settings, then system and change subsystem to «not set». It will link based on which entry point function you have defined.

Please report the compiler and linker command lines that, when run, produced the error messages above. Or, if the build was performed inside VisualStudio, please attach a copy of the build log file.

It appears that a number of object files, none of which contained a compiled Fortran main program, were given to the linker.

You may also check the files in the project and do a «clean and rebuild».

Also, is this a mixed-language (Fortran and C/C++) application? If so, which language has the main program? You may need to recreate the project dependencies as explained in the compiler release notes and here.


It seems there someting wrong with the installation but I am not sure. Everything worked fine before.
May there is someone who has an idea?..

Hi Alex,

This is a linker error and it is not clear for me how it could be related to the update you’ve done. Here are
some details about startup functions:

Console Win32application uses ‘main‘ entry-function — EntryPointSymbolis’mainCRTStartup‘ function
GUI Win32 applicationuses ‘WinMain‘ entry-function — EntryPointSymbol is ‘WinMainCRTStartup‘ function

Entry Point Symbols are defined in Project Settings in ‘Linker -> Advanced -> Entry Point‘.

I would also look at a Character Set option, that is aUNICODE or MBCS, because I had a similar problem in the past.

Best regards,
Sergey

i have similar vf link2001/1120 errors as alex has (project working before but suddenly can’t compile/link after some config setting changed)

in my project, there exist Fortran main program but still having problem to build…

fyi, here are mycompiler and linker command lines

compiler:

/nologo /fpscomp:filesfromcmd /fpscomp:ioformat /fpscomp:logicals /fpscomp:general /Qfp-speculation=safe /module:»x64Release» /object:»x64Release» /Fd»x64Releasevc90.pdb» /libs:static /threads /c

linker:

/OUT:»x64Releasenpm64_cplex.exe» /INCREMENTAL:NO /NOLOGO /MANIFEST /MANIFESTFILE:»C:KCWorksUPLANsrcmodelsnpm64_cplexx64Releasenpm64_cplex.exe.intermediate.manifest» /MANIFESTUAC:»level=’asInvoker’ uiAccess=’false'» /SUBSYSTEM:CONSOLE /STACK:200000000 /ENTRY:»mainCRTStartup» /IMPLIB:»C:KCWorksUPLANsrcmodelsnpm64_cplexx64Releasenpm64_cplex.lib»

thanks for any idea to help

Bernardo, please show the actual error messages. I will comment that your linker setting for /STACK is way too high and will cause you problems running the program. I do not recommend going over 100MB for this, even on x64.

hi steve,

i’m usingIntel Visual Fortran Composer XE 2011 Update 9 Integration for Microsoft Visual Studio* 2008, 12.1.3526.2008 on a 64bit Win7 pc

the actual error messages i got after i clicked ‘rebuild solution’ as following:

————

LINK
: warning LNK4001: no object files specified; libraries used

LINK
: warning LNK4068: /MACHINE not specified; defaulting to X86

LINK
: LNK2001: unresolved
external symbol _mainCRTStartup

fatal error LNK1120: 1 unresolved externals

————

i had no problem build and run the program before with the linker setting for /stack till i encountered this error few days ago (ihave a feeling the project config properties i changed may cause the errors)

by the way, should I choose the compiler selection Platform to ‘x64’ or ‘Win32’ underTools -> Options -> under Intel Visual Fortran
-> Compilers» ?

thanks

You do not use Tools > Options to select a compiler platform — that is used to select which include and library paths are used by default when you do a build in those platforms. You change the solution platform by Build > Configuration Manager, select New… as the platform and it will create an x64 platform for you.

The errors you’re getting suggest that no files are being compiled.

steve,

thanksfor your reply

yes, I can’t even compile any source codes becausethe ‘Compile’ menu bar was ‘disappeared’ from the pull-down menu under ‘Build’ (now, after theBuild > Configuration Manager, there is no menu bar like ‘Compile’ shown)

in fact, i had no problem building my project last week andhave no idea what trap in vf config settings i triggered to make the ‘Compile’ menu bar disappear and then linker error happened !@#$%

i think to re-install my VF to get rid of this problem which had been bothering me few days but I will never know what causes this after installation..

Bernardo,

I believe I know how to fix this. Follow the instructions in the fourth bullet of Step 1 in this article. Let me know if that works.

hi steve,

thank u so much for the ‘key’ to resolve the issue, it WORKS.now, i can rebuild my project w/o problem

just can’t recall when did i blank out the free/fxed format setting???

anyway, many thanks

bernado

It is nothing you did explicitly — some customers find this happens when they install an update. We’re still not sure why.

…I will comment that your linker setting for /STACK is way too high and will cause you problems running
the program.I do not recommend going over 100MB for this, even on x64…

Steve,

Ona 32-bitWindows platformfor some test-cases I useeven higher values for STACK linker option and
they work ( It doesn’t matter thatthese values for a C/C++ applcation ):


// Case 1
//#pragma comment( linker, «/HEAP:1069547520,1069547520» )
//#pragma comment( linker, «/STACK:4194304,4194304» )

// Case 2
//#pragma comment( linker, «/HEAP:536870912,536870912» )
//#pragma comment( linker, «/STACK:536870912,536870912» )

// Case 3
//#pragma comment( linker, «/HEAP:268435456,268435456» )
//#pragma comment( linker, «/STACK:268435456,268435456» )

// Case 4
//#pragma comment( linker, «/HEAP:134217728,134217728» )
//#pragma comment( linker, «/STACK:134217728,134217728» )

Best regards,
Sergey

Sergey, I didn’t say higher values would not work, but I don’t recommend
them. If you find the need to raise the stack size higher, you should
instead be looking at ways to avoid stack usage. This can mean use of
allocatable rather than automatic arrays, the /heap-arrays option or
eliminating the need for the compiler to create temporary array copies
(this last will improve performance.)

Windows limits the stack to 1GB, even on 64-bit systems.

Sergey, I didn’t say higher values would not work, but I don’t recommend them. If you find the need to raise the stack size higher, you should instead be looking at ways to avoid stack usage

In some cases this is simply impossible:

— Case #1: When an applicationneeds to create more than256 threads (with TBB, for example )

— Case #2: Recursive algorithms ( QuickSort on huge arrays orStrassen’s matrix multiplication, for example)

However, I have one case that is «in line» with your point of view: on avery compactembedded platforms
with limited memory resources a significantstack increaseis problematic.

Best regards,
Sergey

Topic: LNK2001: unresolved external symbol _mainCRTStartup  (Read 2359 times)

Hello everyone,
Before starting, I’d like to say that I’m new on this forum, so I hope I’ve posted at the good place (if it’s not the case, I’m sorry).
I took a look on the forum and I saw that this error appears frequently.
There’s my code :

.386
.model flat, stdcall
.stack 1000h ; 4096-sized stack
option casemap : none ; differencies uppercase chars and lowercase ones

include msvcrt.inc
include masm32rt.inc
include masm32.inc
include masm32/m32lib/ltoa.asm ; without, error A2008 syntax error ltoa

includelib masm32.lib
includelib msvcrt.lib
includelib masm32rt.lib

.data
Hello db "Hello, World !", 13, 10 ; string ended with opcode 10 => endline

.data?
value db 64 dup (?)
; according to masm help (help/masmlib section conversion/atoi), 128 bytes are usually sufficient for input, a word is 2 bytes long

.code

main proc
invoke StdOut, addr Hello
invoke StdIn, addr value, 64
mov eax, atol value
add eax, 1
new db " "
ltoa new, addr value
invoke StdOut, addr new

main endp

end main


I found a topic where the error disappeared with the final ‘end main’, but it doesn’t work for me.

That’s the command line :

C:/masm32/bin/ml.exe /c /coff /Cp /nologo /I"C:/" /I"C:/masm32/include/" %file%
C:/masm32/bin/link.exe /subsystem:console /release /version:4.0 /libpath:"C:/" /libpath:"C:/masm32/lib" /out:%app%.exe %app%.obj
(file and app are <path>/<filename>.asm and <path>/<filename>, no problem with that)

I know there’s print macro os MasmBasic lib by @jj2007 but to start, I’d like to understand I/O system in assembly before hide complexity (in another topic, I saw that a display requires 4 lines, right ?).

If it can help you, my final goal is to input two numbers, then display their sum.
But when I tried (with another program) to add two inputs, it displays the char corresponding to the sum of ASCII values.
How can I do ?

(I’m sorry if my English isn’t very good, that’s not my first language)

« Last Edit: May 02, 2021, 11:54:40 PM by hutch— »


Logged


Hi an welcome on board.

.stack 1000h   ; this is not used in Win32. Stack is set in the linker options if you need to.

include masm32rt.inc  ; use this line by itself, it include the normal range of options.

You need a layout like this.

    include masm32includemasm32rt.inc

        .code

start:

    ; all of your code.

end start


Logged


So I write main: … end main, and it works.
I don’t need to change the stack’s size, but I saw it on Internet.

The layout is correct because in the command line, I wrote /I»C:/masm32/include» and /I»C:/».
But ltoa doesn’t seem to be recognized by the linker :
test.asm(24) : error A2008: syntax error : ltoa
test.asm(21) : error A2206: missing operator in expression

(Is this site based in Australia ? It’s quite weird for m to see 06PM, because in France it’s almost 11AM)


Logged


Welcome totosayen_cpp :thumbsup:
you need to put
new db » » in .data section
end strings with 0
«this is a string»,0
and invoke ltoa in similar way you do with other PROC’s like


Logged


Thank you for this welcome !

So, I did some changes (inputs a number, adds 1 and displays the result) :

.386
.model flat, stdcall
option casemap : none ; differencies uppercase chars and lowercase ones

include masm32rt.inc

includelib masm32rt.lib

.data
Hello db "Hello, World !", 13, 10, 0 ; string ended with opcode 10 => endline
new db " ", 0

.data?
value db 64 dup (?)
; according to masm help (help/masmlib section conversion/atoi), 128 bytes are usually sufficient for input, a word is 2 bytes long

.code

main:
invoke StdOut, addr Hello
invoke StdIn, addr value, 64
invoke atol, addr value
add value, 1
invoke ltoa, addr value, addr new
invoke StdOut, addr new
invoke ExitProcess, 0
end main


It compiles and links, but the output seems quite odd.
The program firstly displays «Hello, World !» followed by an endline, as expected.
Then, I input 8 and it ouputs 4206624.

Why this result ?

« Last Edit: April 28, 2021, 11:08:11 PM by totosayen_cpp »


Logged


The «Hello World» is string data where 8 is an integer. Use a string conversion to make 8 into a displayable string.


Logged


You will fail miserably if you don’t practice two things:
1. read the documentation carefully, and try to really understand it
2. comment your code thoroughly

include masm32includemasm32rt.inc

.data
Hello db "Hello, World !", 13, 10, 0 ; string ended with opcode 10 => endline
new db " ", 0

.data?
value dd ?
buffer db 64 dup (?)   ; this buffer serves for what we type
; according to masm help (help/masmlib section conversion/atoi), 128 bytes are usually sufficient for input, a word is 2 bytes long

.code

main:
invoke StdOut, addr Hello
invoke StdIn, addr buffer, 64 ; get a string into the buffer
invoke atol, addr buffer ; convert to a long ("ascii to long")
mov value, eax ; the value was returned in eax
add value, 100 ; add something
invoke ltoa, value, addr new ; convert long to ascii
invoke StdOut, addr new ; print it
invoke ExitProcess, 0
end main


Logged


Hi Toto,

Here is a simple test piece that may be useful to you.

; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

    include masm32includemasm32rt.inc

        .code

start:

    call testbed                        ; call the testbed proc
    exit                                ; the exit macro

; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

testbed proc

    LOCAL var1  :DWORD                  ; create local variables
    LOCAL var2  :DWORD
    LOCAL rslt  :DWORD

    mov var1, 100                       ; load immediate values into variables
    mov var2, 150

    mov eax, var1                       ; load 1st variable into EAX register
    add eax, var2                       ; add var2 to EAX
    mov rslt, eax                       ; store EAX register in variable

    print «Total = »                    ; display leading text
    print ustr$(rslt),13,10             ; display calculation result

    inkey                               ; pause to view the output

    ret

testbed endp

; ¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤¤

end start


Logged


Thank you @jj2007, I’ve read masm32/help/masmlib.chm (conversions/atol) and it doesn’t (at least for me) say where the result is stored.
I’m sorry and I’ll try to search more the next time.

I’m trying this to input the values :

include masm32rt.inc

.data
Hello   db  "Hello, World !", 13, 10, 0 ; string ended with opcode 10 => endline
input1  db "Input a number : "      , 0
input2  db "Input another number : ", 0
plus db " + " , 0
equal db " = " , 0
endline db " ", 13, 10 , 0

.data?
resultInt dd ? ; result (integer) of the 2 numbers
resultStr db ? ; result (string) of the 2 numbers

; according to masm help (help/masmlib section conversion/atoi), 128 bytes are usually sufficient for input, a word is 2 bytes long

buffer1  db 64 dup (?)   ; stores input 1
buffer2  db 64 dup (?) ; stores input 2

.code

inputValue proc text: dword, buffer: dword, value: dword
invoke StdOut, text ; displays text
invoke StdIn, buffer, sizeof buffer ; inputs string
invoke atol, buffer ; converts it into a signed number (dword)
add value, eax ; result stored in eax
mov eax, 0 ; resets eax
invoke StdOut, addr endline ; writes a new line to clean output
ret
inputValue endp

main:
; inputs the two values
invoke inputValue, addr input1, addr buffer1, addr resultInt
invoke inputValue, addr input2, addr buffer2, addr resultInt

; converts back value into a string
invoke ltoa, resultInt, addr resultStr

; displays the result
invoke StdOut, addr buffer1
invoke StdOut, addr plus
invoke StdOut, addr buffer2
invoke StdOut, addr equal
invoke StdOut, addr resultStr
invoke StdOut, addr endline

; ends the process
invoke ExitProcess, 0
end main


But it doesn’t work as expected :

  • The result is always 0 (if I remove addr of resultInt, it doesn’t work; if I declare value param as a lpvoid compilation fails (undefined symbol))
  • When displaying, the first buffer seems empty, whereas the second displays well (with the 2nd input)


Logged


invoke StdIn, buffer, sizeof buffer ; inputs string
Are you sure this is the right «sizeof buffer»? The local argument buffer is a DWORD, i.e. its size is 4 bytes :cool:


Logged


So, is there a way to «dereference» the pointer ?
In C we do :

type func(type* ptr) {
    type val = *ptr;
}

How do you write invoke StdIn, buffer sizeof <dereferenced buffer> ?


Logged


invoke StdIn, buffer, sizeof buffer1 will work. If you insist on following the rules, add another argument to the proc:

inputValue proc text: dword, buffer: dword, value: dword, TheSize
invoke StdIn, buffer, TheSize

invoke inputValue, addr input1, addr buffer1, addr resultInt, sizeof buffer1

Better, avoiding misunderstandings:
inputValue proc text: dword, pBuffer: dword, value: dword, TheSize
invoke StdIn, pBuffer, TheSize

invoke inputValue, addr input1, addr buffer1, addr resultInt, sizeof buffer1


Logged


I added a paramater :

inputValue proc text: dword, buffer: dword, bufferSize: word, value: dword
...
invoke StdIn, buffer, bufferSize
...
inputValue endp

; main :
invoke inputValue, addr input1, addr buffer1, sizeof buffer1, addr resultInt


But I’ve the same problem (console log) :

***********
ASCII build
***********

Microsoft (R) Incremental Linker Version 5.12.8078
Copyright (C) Microsoft Corp 1992-1998. All rights reserved.

Input a number : 7

Input another number : 4

 + 4 = 0


Logged


Please post your complete code with comments.

invoke inputValue, addr input1, addr buffer1, sizeof buffer1, addr resultInt
invoke inputValue, addr input2, addr buffer2, sizeof buffer2, addr resultInt

; converts back value into a string
invoke ltoa, resultInt, addr resultStr


Logged


Sorry, that’s the whole code :

include masm32rt.inc

.data
Hello   db  "Hello, World !", 13, 10, 0 ; string ended with opcode 10 => endline
input1  db "Input a number : "      , 0
input2  db "Input another number : ", 0
plus db " + " , 0
equal db " = " , 0
endline db " ", 13, 10 , 0

.data?
resultInt dd ? ; result (integer) of the 2 numbers
resultStr db ? ; result (string) of the 2 numbers

; according to masm help (help/masmlib section conversion/atoi), 128 bytes are usually sufficient for input, a word is 2 bytes long

buffer1  db 64 dup (?)   ; stores input 1
buffer2  db 64 dup (?) ; stores input 2

.code

inputValue proc text: dword, buffer: dword, bufferSize: word, value: dword
invoke StdOut, text ; displays text
invoke StdIn, buffer, bufferSize ; inputs string
invoke atol, buffer ; converts it into a signed number (dword)
add value, eax ; result stored in eax
mov eax, 0 ; resets eax
invoke StdOut, addr endline ; writes a new line to clean output
ret
inputValue endp

main:
; inputs the two values
invoke inputValue, addr input1, addr buffer1, sizeof buffer1, addr resultInt
invoke inputValue, addr input2, addr buffer2, sizeof buffer2, addr resultInt

; converts back value into a string
invoke ltoa, resultInt, addr resultStr

; displays the result
invoke StdOut, addr buffer1
invoke StdOut, addr plus
invoke StdOut, addr buffer2
invoke StdOut, addr equal
invoke StdOut, addr resultStr
invoke StdOut, addr endline

; ends the process
invoke ExitProcess, 0
end main


Logged


Понравилась статья? Поделить с друзьями:

Читайте также:

  • Link error excel
  • Lines are not coplanar как исправить
  • Lineage error a jni error has occurred please check your installation and try again
  • Lineage 2 crash report как исправить windows 10
  • Line protocol is down как исправить cisco

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

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