- Remove From My Forums
-
Вопрос
-
—— Build started: Project: vball, Configuration: Debug Win32 ——
1>Build started 24-May-11 11:12:32 AM.
1>InitializeBuildStatus:
1> Touching «Debugvball.unsuccessfulbuild».
1>ManifestResourceCompile:
1> All outputs are up-to-date.
1>LINK : error LNK2001: unresolved external symbol _mainCRTStartup
1>c:userssvdocumentsvisual studio 2010ProjectsvballDebugvball.exe : fatal error LNK1120: 1 unresolved externals
1>
1>Build FAILED.
1>
1>Time Elapsed 00:00:02.64
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
code compiled was
#include<iostream>
using namespace
std;int
main()
{
cout<<«Hello
!»;return
0;
}
i
even tried compiling using vs command prompt but even there also following errors occuredC:program
files(x86)Microsoft visual studio 10.0VCINCLUDEcmath(19) : error c2061 : syntax error : identifier ‘acosf’;like
above more than 100 errors occured.
Ответы
-
From the description of your issue, I assume, you created an empty project.
If you want to build a c++ project from scratch do:
In the project wizard go to Projects Types and check Empty Project option (for me its under Visual C++ General). Important: no clr support). Add a file say vball.cpp to your project (because compiler then uses c++, which you need, when using cout. When file
is ending with plain c, VS thinks, it is only c-code, and you get these acosf errors). Copy your code into this file. Try a new build and run.But for beginners, it is far better, to use the wizards to build new projects, in your case, a console-application would be a good choice. Also you ended up with your thread in VS-Debugger Forum which handles debugger problems. For issues like yours, either
Visual C++ General or Visual C++ Language
http://social.msdn.microsoft.com/Forums/en-US/category/visualc
are much better suited.with kind regards
-
Помечено в качестве ответа
2 июня 2011 г. 8:42
-
Помечено в качестве ответа
SpartakusMd 22 / 22 / 9 Регистрация: 29.03.2010 Сообщений: 173 |
||||
1 |
||||
29.01.2011, 21:23. Показов 11308. Ответов 4 Метки нет (Все метки)
Здраствуйте. Вот страница на ideone.com.
Вот вывод: —— Построение начато: проект: Matrice, Конфигурация: Debug Win32 —— СБОЙ построения. Затраченное время: 00:00:01.29
__________________
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
0 |
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 asVAR1
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 anextern "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 asextern
. To fix this issue, use explicitextern
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 ofstrcmp
. 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?».
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 asVAR1
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 anextern "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 asextern
. To fix this issue, use explicitextern
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 ofstrcmp
. 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?».
Содержание
- Ошибка средств компоновщика LNK2001
- Что такое неразрешенный внешний символ?
- Проблемы компиляции и компоновки
- Проблемы кодирования
- Проблемы согласованности
- Ошибки экспортированного файла DEF
- Использовать декорированное имя для поиска ошибки
- Error lnk2001 unresolved external symbol boost
- Answered by:
- Question
Ошибка средств компоновщика LNK2001
Скомпилированный код создает ссылку или вызов символа. Символ не определен ни в одной из библиотек или объектных файлов, поиск которого осуществляется компоновщиком.
Это сообщение об ошибке после неустранимой ошибки LNK1120. Чтобы устранить ошибку LNK1120, сначала исправьте все ошибки LNK2001 и LNK2019.
Существует множество способов получения ошибок LNK2001. Все они используют ссылку на функцию или переменную, которую компоновщик не может Разрешить, или найти определение для. Компилятор может определить, когда код не объявляет символ, но не в том случае, если он не определен . Это связано с тем, что определение может находиться в другом исходном файле или библиотеке. Если код ссылается на символ, но он никогда не определен, компоновщик создает ошибку.
Что такое неразрешенный внешний символ?
Символ — это внутреннее имя функции или глобальной переменной. Это форма имени, используемая или определенная в скомпилированном объектном файле или библиотеке. Глобальная переменная определяется в объектном файле, где для него выделяется хранилище. Функция определена в объектном файле, где размещается скомпилированный код для тела функции. Внешний символ является ссылкой в одном файле объекта, но определен в другой библиотеке или объектном файле. Экспортированный символ — это открытый объект, который становится общедоступным для файлового файла или библиотеки, определяющей его.
Для создания приложения или библиотеки DLL в каждом используемом символе должно быть определено определение. Компоновщик должен Разрешитьили найти определение сопоставления для каждого внешнего символа, на который ссылается каждый файл объекта. Компоновщик создает ошибку, если не удается разрешить внешний символ. Это означает, что компоновщику не удалось найти соответствующее определение экспортированного символа в любом из связанных файлов.
Проблемы компиляции и компоновки
Эта ошибка может возникать:
Если в проекте отсутствует ссылка на библиотеку (. LIB) или Object (. OBJ-файл). Чтобы устранить эту проблему, добавьте в проект ссылку на требуемую библиотеку или файл объекта. Дополнительные сведения см. в разделе lib files as input компоновщика.
Если проект содержит ссылку на библиотеку (. LIB) или Object (. OBJ), который, в свою очередь, требуются символы из другой библиотеки. Это может произойти даже в том случае, если не вызываются функции, вызывающие зависимость. Чтобы устранить эту проблему, добавьте в проект ссылку на другую библиотеку. Дополнительные сведения см. в разделе понимание классической модели для связывания: использование символов в качестве пути.
При использовании параметров /NODEFAULTLIB или /Zl . При указании этих параметров библиотеки, содержащие требуемый код, не будут связаны с проектом, если они не включены явным образом. Чтобы устранить эту проблему, явно включите все библиотеки, используемые в командной строке компоновки. Если при использовании этих параметров отображается множество отсутствующих имен функций CRT или стандартной библиотеки, явно включите библиотеки CRT и библиотеки стандартных библиотек или файлы библиотеки в ссылку.
При компиляции с параметром /CLR . Возможно, отсутствует ссылка на .cctor . Дополнительные сведения об устранении этой проблемы см. в разделе Инициализация смешанных сборок.
Если при построении отладочной версии приложения вы связываетесь с библиотеками в режиме выпуска. Аналогично, если вы используете параметры /MTD или /MDD или определяете _DEBUG , а затем связываетесь с библиотеками выпусков, то во многих других случаях следует рассчитывать на множество потенциальных неразрешенных внешних значений. Связывание сборки в режиме выпуска с отладочными библиотеками также вызывает аналогичные проблемы. Чтобы устранить эту проблему, убедитесь, что вы используете отладочные библиотеки в отладочных сборках и розничных библиотеках в ваших розничных сборках.
Если код ссылается на символ из одной версии библиотеки, но вы связываете другую версию библиотеки. Как правило, нельзя смешивать объектные файлы или библиотеки, созданные для разных версий компилятора. Библиотеки, поставляемые в одной версии, могут содержать символы, которые не могут быть найдены в библиотеках, включенных в другие версии. Чтобы устранить эту проблему, создайте все объектные файлы и библиотеки с одной и той же версией компилятора, прежде чем связывать их друг с другом. дополнительные сведения см. в разделе совместимость двоичных данных C++ между версиями Visual Studio.
Если пути к библиотекам устарели. диалоговое окно сервис > параметры > проекты > VC++ каталоги в области выбор файлов библиотеки позволяет изменить порядок поиска в библиотеке. Папка Компоновщик в диалоговом окне страницы свойств проекта может также содержать неактуальные пути.
при установке нового Windows SDK (возможно, в другое расположение). Необходимо обновить порядок поиска библиотеки, чтобы он указывал на новое расположение. Как правило, путь следует поместить в новый каталог include и lib для пакета SDK перед расположением Visual C++ по умолчанию. Кроме того, проект, содержащий внедренные пути, может по-прежнему указывать на старые пути, которые являются допустимыми, но устарели. Обновите пути для новых функций, добавленных новой версией, которая установлена в другое расположение.
При построении в командной строке и создании собственных переменных среды. Убедитесь, что пути к инструментам, библиотекам и файлам заголовков имеют одинаковую версию. Дополнительные сведения см. в статье Использование набора инструментов MSVC из командной строки.
Проблемы кодирования
Эта ошибка может быть вызвана следующими причинами.
Несовпадение регистра в исходном коде или файле определения модуля (DEF). Например, если вы назначите переменную var1 в одном исходном файле C++ и попытаетесь получить к ней доступ, как VAR1 в другой, возникает эта ошибка. Чтобы устранить эту проблему, используйте согласованное написание имен и имена регистров.
Проект, использующий встраивание функций. Это может произойти при определении функций inline в исходном файле, а не в файле заголовка. Встроенные функции не отображаются за пределами исходного файла, который их определяет. Чтобы устранить эту проблему, определите встроенные функции в заголовках, где они объявляются.
Вызов функции C из программы на языке C++ без использования extern «C» объявления для функции C. Компилятор использует разные внутренние соглашения об именовании символов для кода C и C++. Внутреннее имя символа — это то, что ищет компоновщик при разрешении символов. Чтобы устранить эту проблему, используйте extern «C» обертку для всех объявлений функций C, используемых в коде C++, в результате чего компилятор должен использовать внутреннее соглашение об именовании языка c для этих символов. Параметры компилятора /TP и /TC заставляют компилятор компилировать файлы как C++ или C соответственно, независимо от расширения имени файла. Эти параметры могут привести к тому, что имена внутренних функций отличаются от предполагаемых.
Попытка сослаться на функции или данные, у которых нет внешней компоновки. В C++ встроенные функции и const данные имеют внутреннюю компоновку, если явно не указано в качестве extern . Чтобы устранить эту проблему, используйте явные extern объявления для символов, которые ссылаются вне определяющего исходного файла.
Отсутствует тело функции или определение переменной . Эта ошибка часто возникает при объявлении, но не определении, переменных, функций или классов в коде. Компилятору требуется только прототип функции или extern объявление переменной, чтобы создать объектный файл без ошибок, но компоновщик не может разрешить вызов функции или ссылку на переменную, так как код функции или переменное пространство не зарезервированы. Чтобы устранить эту проблему, обязательно Определите каждую указанную функцию и переменную в исходном файле или библиотеке, на которую вы связываетесь.
Вызов функции, который использует типы возвращаемых значений и параметров или соглашения о вызовах, которые не соответствуют объектам в определении функции. В объектных файлах C++ декорирование имен кодирует соглашение о вызовах, область класса или пространства имен, а также типы возвращаемых данных и параметров функции. Закодированная строка становится частью окончательного декорированного имени функции. Это имя используется компоновщиком для разрешения или сопоставления вызовов функции из других объектных файлов. Чтобы устранить эту проблему, убедитесь, что в объявлении функции, определении и вызовах используются одни и те же области, типы и соглашения о вызовах.
Код C++, который вызывается при включении прототипа функции в определение класса, но не включает реализацию функции. Чтобы устранить эту проблему, обязательно предоставьте определение для всех членов класса, которые вы вызываете.
Попытка вызвать чисто виртуальную функцию из абстрактного базового класса. Чистая виртуальная функция не имеет реализации базового класса. Чтобы устранить эту проблему, убедитесь, что все вызванные виртуальные функции реализованы.
Попытка использовать переменную, объявленную в функции (Локальная переменная), за пределами области этой функции. Чтобы устранить эту проблему, удалите ссылку на переменную, которая не находится в области действия, или переместите переменную в область более высокого уровня.
При построении окончательной версии проекта ATL создается сообщение о том, что код запуска CRT является обязательным. Чтобы устранить эту проблему, выполните одно из следующих действий.
Удалите _ATL_MIN_CRT из списка определений препроцессора, чтобы разрешить включение кода запуска CRT. Дополнительные сведения см. в разделе Страница свойств General (Project).
Если это возможно, удалите вызовы функций CRT, требующих код запуска CRT. Вместо этого используйте эквиваленты Win32. Например, используйте lstrcmp вместо strcmp . Известными функциями, требующими код запуска CRT, являются некоторые функции строк и вычислений с плавающей запятой.
Проблемы согласованности
В настоящее время нет стандарта для декорирования имен C++ между поставщиками компиляторов или даже между разными версиями одного и того же компилятора. Объектные файлы, скомпилированные с разными компиляторами, могут не использовать одинаковую схему именования. Связывание их может вызвать ошибку LNK2001.
Смешивание встроенных и невстроенных параметров компиляции в разных модулях может вызвать ошибку LNK2001. Если библиотека C++ создается с включенной функцией встраивания функций (/Ob1 или /Ob2), но соответствующий заголовочный файл, описывающий функции, отключен (без inline ключевого слова), возникает эта ошибка. Чтобы устранить эту проблему, определите функции inline в файле заголовка, который включается в другие исходные файлы.
Если вы используете #pragma inline_depth директиву компилятора, убедитесь, что задано значение 2 или более, и убедитесь, что вы также используете параметр компилятора /Ob1 или /Ob2 .
Эта ошибка может возникать, если опустить параметр LINK/NOENTRY при создании библиотеки DLL только для ресурсов. Чтобы устранить эту проблему, добавьте параметр/NOENTRY в команду Link.
Эта ошибка может возникать, если в проекте используются неверные параметры/SUBSYSTEM или/ENTRY. Например, при написании консольного приложения и задании/SUBSYSTEM: WINDOWS создается неразрешенная внешняя ошибка для WinMain . Чтобы устранить эту проблему, убедитесь, что вы соответствуете параметрам типа проекта. Дополнительные сведения об этих параметрах и точках входа см. в разделе Параметры компоновщика /SUBSYSTEM и /entry .
Ошибки экспортированного файла DEF
Эта ошибка возникает, когда экспорт, указанный в DEF-файле, не найден. Это может быть вызвано тем, что экспорт не существует, написан неправильно или использует декорированные имена C++. DEF-файл не имеет декорированных имен. Чтобы устранить эту проблему, удалите ненужные экспорты и используйте extern «C» объявления для экспортированных символов.
Использовать декорированное имя для поиска ошибки
Компилятор и компоновщик C++ используют декорирование имен, также называемое искажением имени. Декорирование имен кодирует дополнительные сведения о типе переменной в ее имени символа. Имя символа для функции кодирует свой возвращаемый тип, типы параметров, область и соглашение о вызовах. Это декорированное имя — это имя символа, которое компоновщик ищет для разрешения внешних символов.
Ошибка связи может возникнуть, если объявление функции или переменной не полностью соответствует определению функции или переменной. Это связано с тем, что все различия становятся частью имени символа для сопоставления. Ошибка может возникать даже в том случае, если один и тот же файл заголовка используется как в вызывающем, так и в коде, определяющем код. Это может произойти, если вы компилируете исходные файлы с помощью различных флагов компилятора. Например, если код компилируется для использования __vectorcall соглашения о вызовах, но вы связываетесь с библиотекой, которая ожидает, что клиенты будут вызывать его с помощью соглашения по умолчанию __cdecl или __fastcall вызова. В этом случае символы не совпадают, поскольку соглашения о вызовах различаются.
Чтобы помочь вам найти причину, в сообщении об ошибке отображаются две версии имени. В нем отображается «понятное имя», имя, используемое в исходном коде, и декорированное имя (в круглых скобках). Вам не нужно знать, как интерпретировать декорированное имя. Вы по-прежнему можете выполнять поиск и сравнивать его с другими декорированными именами. Программы командной строки могут помочь найти и сравнить ожидаемое имя символа и фактическое имя символа:
Параметры /EXPORTS и /SYMBOLS программы командной строки DUMPBIN полезны здесь. Они могут помочь определить, какие символы определены в .dll и файлах объектов или библиотек. Можно использовать список символов, чтобы убедиться, что экспортированные декорированные имена соответствуют декорированным именам, которые ищет компоновщик.
В некоторых случаях Компоновщик может сообщать только о декорированном имени символа. Для получения недекорированной формы декорированного имени можно использовать программу командной строки UNDNAME.
Источник
Error lnk2001 unresolved external symbol boost
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I’m using a these libraries DragonFireSDK.lib(from DragonFireSDK — compatible with visual studio and visual studio Express using C++) and sqlite3.lib in my project.
I built the sqlite3.lib in visual studio 2008 and i got the DragonFireSDK.lib file from the SDK team. I linked the sqlite3.lib in my project by following this link http://www.youtube.com/watch?v=BfVP7G4DJkM. When i use only the sqlite3.lib, i’m not getting any link errors. But when i use both the above libraries i get the linking errors. In the first stage i got the following errors,
1>—— Build started: Project: iphoneApp, Configuration: Debug Win32 ——
1> sqlite3.lib(sqlite3.obj) : MSIL .netmodule or module compiled with /GL found; restarting link with /LTCG; add /LTCG to the link command line to improve linker performance
1>LINK : warning LNK4075: ignoring ‘/INCREMENTAL’ due to ‘/LTCG’ specification
1>LIBCMT.lib(_file.obj) : error LNK2005: __lock_file already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(_file.obj) : error LNK2005: __unlock_file already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __initterm_e already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0dat.obj) : error LNK2005: _exit already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __exit already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __cexit already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0dat.obj) : error LNK2005: __amsg_exit already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(fflush.obj) : error LNK2005: _fflush already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(hooks.obj) : error LNK2005: «void __cdecl terminate(void)» (?terminate@@YAXXZ) already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(invarg.obj) : error LNK2005: __invoke_watson already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(invarg.obj) : error LNK2005: __invalid_parameter already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xi_a already defined in MSVCRTD.lib(cinitexe.obj)
1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xi_z already defined in MSVCRTD.lib(cinitexe.obj)
1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xc_a already defined in MSVCRTD.lib(cinitexe.obj)
1>LIBCMT.lib(crt0init.obj) : error LNK2005: ___xc_z already defined in MSVCRTD.lib(cinitexe.obj)
1>LIBCMT.lib(mlock.obj) : error LNK2005: __unlock already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(mlock.obj) : error LNK2005: __lock already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(winxfltr.obj) : error LNK2005: __XcptFilter already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LIBCMT.lib(crt0.obj) : error LNK2005: _mainCRTStartup already defined in MSVCRTD.lib(crtexe.obj)
1>LIBCMT.lib(errmode.obj) : error LNK2005: ___set_app_type already defined in MSVCRTD.lib(MSVCR100D.dll)
1>LINK : warning LNK4098: defaultlib ‘MSVCRTD’ conflicts with use of other libs; use /NODEFAULTLIB:library
1>LINK : warning LNK4098: defaultlib ‘MSVCRT’ conflicts with use of other libs; use /NODEFAULTLIB:library
1>LINK : warning LNK4098: defaultlib ‘LIBCMT’ conflicts with use of other libs; use /NODEFAULTLIB:library
1>MSVCRTD.lib(crtexe.obj) : error LNK2001: unresolved external symbol _main
1>LIBCMT.lib(crt0.obj) : error LNK2001: unresolved external symbol _main
1>c:userspriyadocumentsvisual studio 2010ProjectsiphoneAppDebugiphoneApp.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
Источник
Topic: error LNK2001: unresolved external symbol _WinMainCRTStartup (Read 22121 times)
mutabor
Hello,
I´m a newbie in c++ AND Code::Blocks, so maybe someone can help me to solve the following problem:
I´m using Microsoft Platform SDK and Microsoft Visual C++ Toolkit 2003.
I try to build a little WIN32GuiApplication (-Projekt), just for testing.
Here is my code:
********************************************
#include <windows.h>
int WINAPI main(HINSTANCE hInstance,
HINSTANCE hPrevInstance,
LPSTR lpCmdLine,
int nCmdShow)
{
MessageBox(0, «Nachricht», «Titel», MB_OK);
return 0;
}
******************************************
When I try to compile the source, I get the following error message:
error LNK2001: unresolved external symbol _WinMainCRTStartup
I searched Google and I think it has something to do with the entry-point of the application (?).
So I think I have to change some Linker-Options or whatever ?!
Could someone please tell me, how to solve this problem and getting the source compiled?
Thank you, mutabor
Logged
error LNK2001: unresolved external symbol _WinMainCRTStartup
This is an linker type error implies the idea that you are missing an needed library.
I suggest it might be the Library MSVCRT. I have no idea if that is the Library name or not.
What is your OS? XP, Vista, etc.
What version of the Platform SDK? Some of the new SDKs may have issues with 2003 Toolkit; I can not remember if that is so or not.
Tim S
« Last Edit: January 25, 2008, 09:33:10 am by stahta01 »
Logged
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.
—
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org
Try compiling in release and post your build log with full compiler logging on.
[full compiler logging]
Settings -> Compiler and Debugger -> Tab «Other» -> Compiler logging = «Full command line».
Tim S
Note: I installed an PSDK called PSDK-x86.exe dated 2005/2006; no idea where to download it from.
Google suggested it was this link I got it from
http://www.microsoft.com/downloads/details.aspx?FamilyId=A55B6B43-E24F-4EA3-A93E-40C0EC4F68E5&displaylang=en
-------------- Build: Release in Test ---------------cl.exe /nologo /W3 /Og /Ox /DNDEBUG /I"C:Program FilesMicrosoft Platform SDKinclude" /I"C:Program FilesMicrosoft Visual C++ Toolkit 2003include" /IF:SourceCodeProjectssokobanksokoban-svnTest /c main.cpp /FoobjReleasemain.obj
main.cpp
link.exe /nologo /subsystem:windows /LIBPATH:"C:Program FilesMicrosoft Platform SDKlib" /LIBPATH:"C:Program FilesMicrosoft Visual C++ Toolkit 2003lib" /out:binReleaseTest.exe gdi32.lib user32.lib kernel32.lib objReleasemain.obj
Output size is 22.50 KB
« Last Edit: January 25, 2008, 09:41:42 am by stahta01 »
Logged
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.
—
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org
mutabor
Hi Tim,
thank you for your replies!
I am using WindowsXP, Microsoft Platform SDK and Microsoft Visual C++ Toolkit 2003.
I searched for the msvcrt.lib in the Toolkit/Lib folder and only found it in an AMD64- and IA64-folder (!), so I think its the wrong (64-bit) version ?!
Do I have to get an other version of the msvcrt.lib or do I have to download the whole SDK again?
I admit, that I am a little bit confused
Here is, what I get from Code:Blocks Build Log:
————— Build: default in Windows —————
link.exe /nologo /subsystem:windows /LIBPATH:»C:ProgrammeMicrosoft Visual C++ Toolkit 2003lib» /out:Windows.exe gdi32.lib user32.lib kernel32.lib .objsmain.obj
LINK : error LNK2001: unresolved external symbol _WinMainCRTStartup
Windows.exe : fatal error LNK1120: 1 unresolved externals
Process terminated with status 1 (0 minutes, 1 seconds)
2 errors, 0 warnings
Any help would be great!
Thanx, mutabor
« Last Edit: January 25, 2008, 06:02:14 pm by mutabor »
Logged
————— Build: default in Windows —————
LINK : error LNK2001: unresolved external symbol _WinMainCRTStartup
…mind using Google before asking?
http://www.google.de/search?q=unresolved+external+symbol+_WinMainCRTStartup
Note that compiler errors are an issue of the *compiler*. We can’t know all compiler in detail. So when such things happen — use Google and/or contact the compiler devs.
With regards, Morten.
Logged
You are missing the Linker search Directory of $(#psdk.lib)
Steps to fix are
1. Create Global Variable psdk
a. «Settings» -> «Global Variables»
b. Look for psdk in «Current Variable» lookup/downdown list
c1. If there fix/verify value of «Base»
Mine is C:Program FilesMicrosoft Platform SDK
c2. if not there Add
i. Click on new on same line as «Current Variable»
ii. Use psdk as «New Variable» name
iii. Set Base to proper path in my case it was
C:Program FilesMicrosoft Platform SDK
2. Add Linker search Directory of $(#psdk.include)
a. «Project» -> «Build Options»
b. Select the project name the highest item in left window
c. Click on Tab «search directories»
d. verify/add $(#psdk.include) under «Compiler» Tab
e. verify/add $(#psdk.lib) under «Linker» tab
Note: My most resent PSDK did not work with Toolkit 2003, but I have no idea if that is your problem, what PSDK are you using? Needed if the above directions do not fix problems.
Note: I need to know if you are compiling release which defines NDEBUG or debug which defines _DEBUG if the above info does not fix problem.
Tim S
« Last Edit: January 26, 2008, 06:50:12 am by stahta01 »
Logged
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.
—
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org
Read, my prior post for what I think is the problem, below answers to some of your questions.
Tim S
I searched for the msvcrt.lib in the Toolkit/Lib folder and only found it in an AMD64- and IA64-folder (!), so I think its the wrong (64-bit) version ?!
I only found msvcrt.lib in the same places in the PSDK (MS Platform SDK), do not think that is reason to believe SDK bad.
Do I have to get an other version of the msvcrt.lib or do I have to download the whole SDK again?
I admit, that I am a little bit confused![]()
If you give me the url or version of your PSDK? I can try it, to see if it works OK, may take awhile to download took me about 2 hours to do the old PSDK I just did of PSDK-x86.exe it’s a web install file of 1.3 megs so it just install the files that urls are inside the exe.
Tim S
Logged
C Programmer working to learn more about C++ and Git.
On Windows 7 64 bit and Windows 10 32 bit.
On Debian Stretch, compiling CB Trunk against wxWidgets 3.0.
—
When in doubt, read the CB WiKi FAQ. http://wiki.codeblocks.org
Как говорят, «или крест снимите, или трусы наденьте». И учите понятие «единица компиляции».
По какой схеме устроен ваш проект? «Одна единица компиляции» или «много единиц компиляции»?
Си недалеко ушёл от ассемблеров. А в ассемблерах программа компилировалась по частям и собиралась воедино линкером (компоновщиком, редактором связей) — в те времена кода было много, а данных мало. Многие из ошибок невозможно было определить, не запустив линкер. Си++ пользуется многими из архитектурных особенностей ассемблеров и Си — по крайней мере ни одно из модульных решений не стало рекомендацией (кроме костыля extern template class
).
Но как говорить «переменная/функция есть, такого-то типа и в другой единице компиляции»? Для этого есть прототипы функций и extern-определения переменных. Их обычно вносят в заголовочные файлы с таким требованием: ничего, что находится в заголовочном файле, не должно производить кода. А код производят…
• Глобальные переменные (без typedef, extern).
• Нешаблонные функции (кроме inline).
• Полностью специализированные шаблонные функции (кроме inline).
• Команда «специализировать шаблон» (template class).
При этом…
• Функции в теле struct/class автоматически inline и кода не производят.
• Для неявной специализации шаблонов существуют обходы — код генерируется дважды, но ошибки не выдаёт.
• «Свой» хедер обычно включают первым, чтобы убедиться, что в нём нет недостающих зависимостей.
В системе «одна единица компиляции» всё просто: есть ровно один файл, подлежащий компиляции. Тогда в хедерных файлах вполне могут быть конструкции, производящие код.
Системы «одна единица компиляции» и «много единиц компиляции» можно комбинировать, но надо знать:
• Все хедеры, которые производят код, должны подключаться из одной-единственной единицы компиляции. Надо чётко осознавать, из какой, и не подключать из чужих.
• У библиотеки всё равно должен быть хедер-фасад, не производящий кода и предназначенный для стыковки с другими единицами компиляции.
Такая конструкция ускоряет полную перекомпиляцию и часто применяется для библиотек, но надо знать: огромные библиотеки вроде SqLite, в 5 мегабайт препроцессированного кода, мешают распараллеливанию компиляции (ибо пока откомпилируется SqLite, остальные процессоры вполне себе соберут остальную программу).
// В схеме «одна единица компиляции»: ничего не делать.
// В схеме «много единиц компиляции»: лишняя зависимость; унести в unit1.cpp
#include <cstdlib>
// В схеме «одна единица компиляции»: убрать extern.
// В схеме «много единиц компиляции»: завести unit1.cpp, там сделать MyType x;
extern MyType X;
// В схеме «одна единица компиляции»: ничего не делать.
// В схеме «много единиц компиляции»: перенести функцию в unit1.cpp, оставив в .h только прототип.
void XReset() {}