Определение
Данная ошибка означает, что в процессе компоновки программы, компоновщик не смог найти определение некоторой сущности, на которую есть ссылка (попытка использования) в программе.
К таким сущностям может относиться, например, функция или переменная.
Причины и решения
Возможных причин появления ошибки может быть несколько и это зависит от того, что представляет из себя собираемый проект. Всё множество ситуаций можно разбить на две большие группы:
Используются сторонние библиотеки
-
Не указана необходимая (статическая) библиотека для компоновщика.
Например, к проекту подключен только
*.h
файл с объявлениями, но отсутствует код реализации, обычно это*.lib
или*.a
файлы (в зависимости от используемой системы).
Требуется явно подключить библиотеку к проекту.
-
Для Visual C++ это можно сделать добавлением следующей строки прямо в код:
#pragma comment(lib, "libname.lib")
-
Для
gcc/clang
требуется указать файл через ключ-l
(эль) -
Для Qt в .pro файле нужно использовать переменную
LIBS
:LIBS += -L[путь_к_библиотеке] -l[имя_библиотеки]
-
Для системы сборки
cmake
естьtarget_link_libraries
.
-
Библиотека указана, но необходимая сущность, например, класс или функция фактически не экспортируется из библиотеки. Под Windows это может возникать из-за отсуствия
__declspec(dllexport)
перед сущностью. Обычно это решается макросами. Данная ситуация чаще всего характерна именно для библиотек, находящихся в процессе разработки, и доступных для модификации самому разработчику, нежели для каких-то стабильных версий действительно внешних для проекта библиотек. После разрешения экспортирования библиотеку, конечно же, нужно пересобрать перед непосредственным использованием проблемной сущности. -
Библиотека указана, но не совпадает разрядность библиотеки и компилируемого кода.
В общем случае, разрядность собираемого проекта (приложения или библиотеки) должна совпадать с разрядностью используемой сторонней библиотеки. Обычно производители библиотек предоставляют возможность выбора 32 или 64 бит версию использовать. Если библиотека поставляется в исходных кодах и собирается отдельно от текущего проекта, нужно также выбрать правильную разрядность.
-
Библиотека указана, но она собрана для другой (не совместимой) ОС.
Например при сборке проекта в Windows осуществляется попытка использовать бинарный файл, собранный для Linux. В данном случае нужно использовать файлы, подходящие для вашей ОС.
-
Библиотека указана, но она собрана другим компилятором, не совместимым с используемым.
Объектные файлы, полученные путем сборки C++ кода разными компиляторами для одной и той же ОС могут быть бинарно несовместимы друг с другом. Требуется использовать совместимые (скорее всего и вовсе одинаковые) компиляторы.
-
Библиотека указана, и собрана тем же компилятором, что и основной проект, но используются разные версии Run-Time библиотек.
Например, для Visual C++ возможна ситуация, когда библиотека собрана с ключом
/MDd
, а основной проект с/MTd
. Требуется задать ключи так, чтобы использовались одинаковые версии Run-Time библиотек.
Сторонние библиотеки не используются
-
Просто отсутствует определение функции.
void f(int); // всего лишь объявление. Нет `тела` функции int main(){ f(42); // undefined reference to `f(int)' }
Требуется добавить определение функции
f
:void f(int) { // тело функции }
Может быть ещё частный случай с ошибкой вида:
undefined reference to `vtable for <имя_класса>`
Такая ошибка возникает, если объявленная виртуальная функция класса, не являющаяся чистой (
=0
), не содержит реализации.class C { virtual void f(int); };
Нужно такую реализацию добавить. Если это делается вне класса, надо не забыть указать имя проблемного класса, иначе это будет просто свободная функция, которая не устраняет указанную проблему:
void C::f(int) { // виртуальная функция-член вне определения класса // тело функции } void f(int) { // свободная функция, не устраняющая проблему // тело функции }
Аналогичная ситуация может возникать при использовании пространств имён, когда объявлении функции находится в пространстве имён:
// В заголовочном файле namespace N { void f(int); };
а при реализации указать это пространство имён забыли:
// В файле реализации void f(int) { // функция в глобальном пространстве имён, не устраняющая проблему // тело функции } namespace N { void f(int) { // функция в нужном пространстве имён // тело функции } } // конец пространства имён
Стоит заметить, что C++ разрешает перегрузку функций (существование одноимённых функций, но с разным набором параметров), и в этом случае важно, чтобы сигнатуры функций при объявлении и определении совпадали. Например, вместо объявленной
void f(int)
была реализована другая:void f(const char*) { // const char* вместо int // тело функции }
При вызове
f(42)
будет ошибка:undefined reference to `f(int)'
Наличие связки шаблонного класса и дружественной функции также может приводить к ошибке. Например:
template <class T> struct C { friend void f(C<T>); // объявляет *НЕ*шаблонную дружественную функцию }; template <class T> // определяет шаблонную функцию void f(C<T>) { } int main() { C<int> c; f(c); // undefined reference to `f(C<int>)' }
Чтобы объявить шаблонную дружественную функцию, требуется добавить указание шаблонности:
template <class T> struct C { template <class V> // добавили шаблонность для friend функции friend void f(C<T>); };
Важно, что имя шаблонного параметра для дружественной функции должно отличаться от имени параметра шаблонного класса
T
, т.к. иначе будет ошибка о сокрытии имени. В частном случае имя класса можно вовсе не указывать, и оставитьtemplate <class>
. Но это не всегда будет правильным решением, т.к. фактически могла потребоваться дружественная специализация шаблона функции, а не сама шаблонная функция. Подробнее об использовании дружественных функций в шаблонном классе можно ознакомиться здесь. -
Отсутствует определение статической переменной класса.
struct S { static int i; }; int main() { S s; s.i = 42; // undefined reference to `S::i' }
Нужно добавить определение (выделить память) переменной:
int S::i;
-
Неправильная реализация шаблонного кода.
Например, реализация шаблонного кода помещена в
*.cpp
файл, хотя она должна находиться полностью в подключаемом*.h
файле. Это требуется по той причине, что компилятор обрабатывает каждый модуль независимо, и в момент инстанцирования шаблона (подстановки конкретного типа) код его реализации должен быть виден. При этом если возможные типы шаблона известны заранее, можно произвести инстанцирование сразу рядом с телом шаблона и не предоставлять его наружу в исходном коде заголовочного файла. Пример:// unit.h #pragma once template <class T> T f(T); // объявление шаблона без реализации
// unit.cpp #include "unit.h" template <class T> T f(T t) { return t + t; } // реализация шаблона template int f<int>(int); // явное инстанцирование для int template double f<double>(double); // явное инстанцирование для double
// main.cpp #include "unit.h" int main() { f(2); // ok int f(1.5); // ok double f('a'); // undefined reference to `char f<char>(char)' }
-
Файл с кодом не был скомпилирован.
Например, в случае использования make-файла не было прописано правило построения файла, а в случае использования IDE типа Visual Studio
*.cpp
файл не добавлен в список файлов проекта. -
Виртуальная функция в базовом классе не объявлена как
= 0
(pure-virtual).struct B { void virtual f(); }; struct D : B { void f() {} }; int main() { D d; }
При использовании иерархии классов функция в базовом классе, не имеющая реализации должна быть помечена как «чистая»:
struct B { void virtual f() = 0; };
-
Имя не имеет внешнего связывания.
Например, есть объявление функции
f
в модулеА
и даже ее реализация в модулеB
, но реализация помечена какstatic
:// A.cpp void f(); int main() { f(); // undefined reference to `f()' } // B.cpp static void f() {}
Аналогичная ситуация может возникнуть при использовании безымянного пространства имен:
// B.cpp namespace { void f() {} }
Или даже при наличии
inline
у функции:// B.cpp inline void f() {}
title | description | ms.date | f1_keywords | helpviewer_keywords | no-loc | ||||||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
Linker Tools Error LNK2019 |
All about the Microsoft Visual Studio Linker error LNK2019 and how to diagnose and correct it in C and C++ code. |
09/07/2022 |
LNK2019 |
|
|
Linker Tools Error LNK2019
unresolved external symbol ‘symbol‘ referenced in function ‘function‘
The compiled code for function makes a reference or call to symbol, but the linker can’t find the symbol definition in any of the libraries or object files.
This error message is followed by fatal error LNK1120. To fix error LNK1120, you must fix all LNK2001 and LNK2019 errors first.
Possible causes
There are many ways to get this error. All of them involve a reference to a function or variable that the linker couldn’t resolve, or find a definition for. The compiler can identify when a symbol isn’t declared, but it can’t tell when the symbol isn’t defined. It’s because the definition may be in a different source file or library. If a symbol is referred to but never defined, the linker generates an unresolved external symbol error.
Here are some common problems that cause LNK2019:
The source file that contains the definition of the symbol isn’t compiled
In Visual Studio, make sure the source file that defines the symbol gets compiled as part of your project. Check the intermediate build output directory for a matching .obj file. If the source file isn’t compiled, right-click on the file in Solution Explorer, and then choose Properties to check the properties of the file. The Configuration Properties > General page should show an Item Type of C/C++ Compiler. On the command line, make sure the source file that contains the definition is compiled.
The object file or library that contains the definition of the symbol isn’t linked
In Visual Studio, make sure the object file or library that contains the symbol definition is linked as part of your project. On the command line, make sure the list of files to link includes the object file or library.
The declaration of the symbol isn’t spelled the same as the definition of the symbol
Verify you use the correct spelling and capitalization in both the declaration and the definition, and wherever the symbol is used or called.
A function is used but the type or number of the parameters don’t match the function definition
The function declaration must match the definition. Make sure the function call matches the declaration, and that the declaration matches the definition. Code that invokes function templates must also have matching function template declarations that include the same template parameters as the definition. For an example of a template declaration mismatch, see sample LNK2019e.cpp in the Examples section.
A function or variable is declared but not defined
LNK2019 can occur when a declaration exists in a header file, but no matching definition is implemented. For member functions or static data members, the implementation must include the class scope selector. For an example, see Missing Function Body or Variable.
The calling convention is different between the function declaration and the function definition
Some calling conventions (__cdecl
, __stdcall
, __fastcall
, and __vectorcall
) are encoded as part of the decorated name. Make sure the calling convention is the same.
A symbol is defined in a C file, but declared without using extern "C"
in a C++ file
A file that’s compiled as C creates decorated names for symbols that are different from the decorated names for the same symbols declared in a C++ file, unless you use an extern "C"
modifier. Make sure the declaration matches the compilation linkage for each symbol. Similarly, if you define a symbol in a C++ file that will be used by a C program, use extern "C"
in the definition.
A symbol is defined as static and then later referenced outside the file
In C++, unlike C, global constants have static
linkage. To get around this limitation, you can include the const
initializations in a header file and include that header in your .cpp files, or you can make the variable non-constant and use a constant reference to access it.
A static member of a class isn’t defined
A static class member must have a unique definition, or it will violate the one-definition rule. A static class member that can’t be defined inline must be defined in one source file by using its fully qualified name. If it isn’t defined at all, the linker generates LNK2019.
A build dependency is only defined as a project dependency in the solution
In earlier versions of Visual Studio, this level of dependency was sufficient. However, starting with Visual Studio 2010, Visual Studio requires a project-to-project reference. If your project doesn’t have a project-to-project reference, you may receive this linker error. Add a project-to-project reference to fix it.
An entry point isn’t defined
The application code must define an appropriate entry point: main
or wmain
for console applications, and WinMain
or wWinMain
for Windows applications. For more information, see main
function and command-line arguments or WinMain
function. To use a custom entry point, specify the /ENTRY
(Entry-Point Symbol) linker option.
You build a console application by using settings for a Windows application
If the error message is similar to unresolved external symbol WinMain referenced in function function_name, link by using /SUBSYSTEM:CONSOLE
instead of /SUBSYSTEM:WINDOWS
. For more information about this setting, and for instructions on how to set this property in Visual Studio, see /SUBSYSTEM
(Specify Subsystem).
You attempt to link 64-bit libraries to 32-bit code, or 32-bit libraries to 64-bit code
Libraries and object files linked to your code must be compiled for the same architecture as your code. Make sure the libraries your project references are compiled for the same architecture as your project. Make sure the /LIBPATH
or Additional Library Directories property points to libraries built for the correct architecture.
You use different compiler options for function inlining in different source files
Using inlined functions defined in .cpp files and mixing function inlining compiler options in different source files can cause LNK2019. For more information, see Function Inlining Problems.
You use automatic variables outside their scope
Automatic (function scope) variables can only be used in the scope of that function. These variables can’t be declared extern
and used in other source files. For an example, see Automatic (Function Scope) Variables.
You call intrinsic functions or pass argument types to intrinsic functions that aren’t supported on your target architecture
For example, if you use an AVX2 intrinsic, but don’t specify the /ARCH:AVX2
compiler option, the compiler assumes that the intrinsic is an external function. Instead of generating an inline instruction, the compiler generates a call to an external symbol with the same name as the intrinsic. When the linker tries to find the definition of this missing function, it generates LNK2019. Make sure you only use intrinsics and types supported by your target architecture.
You mix code that uses native wchar_t
with code that doesn’t
C++ language conformance work that was done in Visual Studio 2005 made wchar_t
a native type by default. If not all files have been compiled by using the same /Zc:wchar_t
settings, type references may not resolve to compatible types. Make sure wchar_t
types in all library and object files are compatible. Either update from a wchar_t
typedef, or use consistent /Zc:wchar_t settings when you compile.
You get errors for *printf*
and *scanf*
functions when you link a legacy static library
A static library that was built using a version of Visual Studio before Visual Studio 2015 may cause LNK2019 errors when linked with the UCRT. The UCRT header files <stdio.h>
, <conio.h>
, and <wchar.h>
now define many *printf*
and *scanf*
variations as inline
functions. The inlined functions are implemented by a smaller set of common functions. Individual exports for the inlined functions aren’t available in the standard UCRT libraries, which only export the common functions. There are a couple of ways to resolve this issue. The method we recommend is to rebuild the legacy library with your current version of Visual Studio. Make sure the library code uses the standard headers for the definitions of the *printf*
and *scanf*
functions that caused the errors. Another option for a legacy library that you can’t rebuild is to add legacy_stdio_definitions.lib
to the list of libraries you link. This library file provides symbols for the *printf*
and *scanf*
functions that are inlined in the UCRT headers. For more information, see the Libraries section in Overview of potential upgrade issues.
Third-party library issues and vcpkg
If you see this error when you’re trying to configure a third-party library as part of your build, consider using vcpkg. vcpkg is a C++ package manager that uses your existing Visual Studio tools to install and build the library. vcpkg supports a large and growing list of third-party libraries. It sets all the configuration properties and dependencies required for successful builds as part of your project.
Diagnosis tools
Sometimes it’s difficult to tell why the linker can’t find a particular symbol definition. Often the problem is that you haven’t included the code that contains the definition in your build. Or, build options have created different decorated names for external symbols. There are several tools and options that can help you diagnose LNK2019 errors.
-
The
/VERBOSE
linker option can help you determine which files the linker references. This option can help you verify whether the file that contains the definition of the symbol is included in your build. -
The
/EXPORTS
and/SYMBOLS
options of the DUMPBIN utility can help you discover which symbols are defined in your .dll and object or library files. Make sure the exported decorated names match the decorated names the linker searches for. -
The UNDNAME utility can show you the equivalent undecorated external symbol for a decorated name.
Examples
Here are several examples of code that causes LNK2019 errors, together with information about how to fix the errors.
A symbol is declared but not defined
In this example, an external variable is declared but not defined:
// LNK2019.cpp // Compile by using: cl /EHsc /W4 LNK2019.cpp // LNK2019 expected extern char B[100]; // B isn't available to the linker int main() { B[0] = ' '; // LNK2019 }
Here’s another example where a variable and function are declared as extern
but no definition is provided:
// LNK2019c.cpp // Compile by using: cl /EHsc LNK2019c.cpp // LNK2019 expected extern int i; extern void g(); void f() { i++; g(); } int main() {}
Unless i
and g
are defined in one of the files included in the build, the linker generates LNK2019. You can fix the errors by including the source code file that contains the definitions as part of the compilation. Alternatively, you can pass .obj
files or .lib
files that contain the definitions to the linker.
A static data member is declared but not defined
LNK2019 can also occur when a static data member is declared but not defined. The following sample generates LNK2019, and shows how to fix it.
// LNK2019b.cpp // Compile by using: cl /EHsc LNK2019b.cpp // LNK2019 expected struct C { static int s; }; // Uncomment the following line to fix the error. // int C::s; int main() { C c; C::s = 1; }
Declaration parameters don’t match the definition
Code that invokes function templates must have matching function template declarations. Declarations must include the same template parameters as the definition. The following sample generates LNK2019 on a user-defined operator, and shows how to fix it.
// LNK2019e.cpp // compile by using: cl /EHsc LNK2019e.cpp // LNK2019 expected #include <iostream> using namespace std; template<class T> class Test { // The operator<< declaration doesn't match the definition below: friend ostream& operator<<(ostream&, Test&); // To fix, replace the line above with the following: // template<typename T> friend ostream& operator<<(ostream&, Test<T>&); }; template<typename T> ostream& operator<<(ostream& os, Test<T>& tt) { return os; } int main() { Test<int> t; cout << "Test: " << t << endl; // LNK2019 unresolved external }
Inconsistent wchar_t type definitions
This sample creates a DLL that has an export that uses WCHAR
, which resolves to wchar_t
.
// LNK2019g.cpp // compile with: cl /EHsc /LD LNK2019g.cpp #include "windows.h" // WCHAR resolves to wchar_t __declspec(dllexport) void func(WCHAR*) {}
The next sample uses the DLL in the previous sample, and generates LNK2019 because the types unsigned short*
and WCHAR*
aren’t the same.
// LNK2019h.cpp // compile by using: cl /EHsc LNK2019h LNK2019g.lib // LNK2019 expected __declspec(dllimport) void func(unsigned short*); int main() { func(0); }
To fix this error, change unsigned short
to wchar_t
or WCHAR
, or compile LNK2019g.cpp by using /Zc:wchar_t-
.
See also
For more information about possible causes and solutions for LNK2019, LNK2001, and LNK1120 errors, see the Stack Overflow question: What is an undefined reference/unresolved external symbol error and how do I fix it?
.
I’m trying to run a program but it won’t compile, I get errors. I have changed things, but doesn’t seem to work. The code is this:
#include <iostream>
#include <string>
#include "StackLS.h"
using namespace std;
int main()
{
int answer;
char symbol;
char n, N;
StackLS stack;
bool balenced = true;
do {
cout << " ********** MENU ********** " << endl;
cout << " 1. Basic Brackets () " << endl;
cout << " 2. Standard Brackets ()[]{} " << endl;
cout << " 3. User-Defined brackets " << endl;
cout << " Please enter your choice: " << endl;
switch (answer){
case 1:
cout << "Current Setting: () " << endl;
cout << "Enter your expression followed by a ; : " << endl;
cin >> symbol;
do {
if (symbol = '(')
stack.push( '(' );
else
if (symbol = ')' )
{
if (stack.isEmpty())
balenced = false;
else {
symbol = stack.top();
stack.pop();
}
if (balenced)
cout << "Expression is well-formed" << endl;
else
cout << "Expression is not well-formed" << endl;
}
}
while (symbol != ';' && balenced);
stack.pop();
}
}
while (answer != 'n' || 'N');
} // end main
I haven’t finished the program. I wanted to make sure that what I have so far will compile before I move on to the next case. Now I will post the errors I am getting. They are:
-
1>e:c++ language 2well-formed expression checker solutionwell-formed expression checker projectmain.cpp(11): warning C4101: ‘n’ : unreferenced local variable
-
1>e:c++ language 2well-formed expression checker solutionwell-formed expression checker projectmain.cpp(11): warning C4101: ‘N’ : unreferenced local variable
-
1>e:c++ language 2well-formed expression checker solutionwell-formed expression checker projectmain.cpp(22): warning C4700: uninitialized local variable ‘answer’ used
1>ManifestResourceCompile:
1> All outputs are up-to-date.
-
1>main.obj : error LNK2019: unresolved external symbol «public: int __thiscall StackLS::top(void)const » (?top@StackLS@@QBEHXZ) referenced in function _main
-
1>main.obj : error LNK2019: unresolved external symbol «public: void __thiscall StackLS::push(int const &)» (?push@StackLS@@QAEXABH@Z) referenced in function _main
-
1>E:C++ language 2Well-Form ed Expression Checker SolutionDebugWell-Formed Expression Checker Project.exe : fatal error LNK1120: 2 unresolved externals
Thanks for the help.
Peter Wood
23.7k5 gold badges60 silver badges98 bronze badges
asked Apr 18, 2012 at 4:07
4
The warnings are just that — warnings. They don’t stop your program from compiling, but you should look at them and try to fix them.
Your program actually compiles OK; the errors are keeping it from linking. That means that after your code has been compiled into machine code, and it’s being built into a *.exe
file,it turns out that some pieces are missing. It looks as if the StackLS.h
file comes with either a C++ source file, or a *.lib or *.dll file; whatever you have, those need to be included when the executable is built, to supply those missing pieces.
answered Apr 18, 2012 at 4:11
6
It has compiled, you got some Warning about unused Variables.
Linking has failed and so what you are missing is the file where StackLS is implemented.
Just including the header does not makes them «implemented».
So you need something like
StackLS.cpp or the like
You don’t have posted that.
answered Apr 18, 2012 at 4:12
FriedrichFriedrich
5,90625 silver badges45 bronze badges
2
The problem is (probably) not with your code, but with the way in which you are invoking your compiler/linker.
You need to compile the source file where int StackLS::top() const
and void StackLS::push(int const &)
are defined, and give the result to your linker that when linking your executable.
answered Apr 18, 2012 at 4:13
MankarseMankarse
39.7k10 gold badges97 silver badges140 bronze badges
You program used a library called StackLS. This could either be precompiled library or some source code.
You add references to this library using the #include "StackLS.h"
, to allow the compiler to compile your code. This creates a compiled version of your code.
The next stage is linking your compiled code with the compiled StackLS library. This is the job of the Linker. These days the same program (compiler) usually makes all the calls needed to do this step too (though you can link your self), though technically it’s a different step to compilation.
If StackLS is your code, then you must compile that too, or if it’s a precompiled library, you need to tell the linker where to find it.
In your make file, you need to add a reference to the StackLS source code or library (it’s usually a .dll or .lib type file in this case).
answered Apr 18, 2012 at 4:16
Preet SanghaPreet Sangha
64.4k18 gold badges145 silver badges213 bronze badges
Remove the lines:
char n, N;
StackLS stack;
and see how you go.
answered Apr 18, 2012 at 4:13
siensien
1692 silver badges5 bronze badges
0
- Remove From My Forums
-
Question
-
Hello! I have been getting this error message upon building my program : LNK2019 unresolved external symbol _main referenced in function «int __cdecl invoke_main(void)» (?invoke_main@@YAHXZ). I have already researched about this error, but I have
found little helpful results towards solving it. I have also tested out some changes in the properties, but many lead to the same error or more. Here is the code:#include <Windows.h>
int ScreenWidth, ScreenHeight;
int Interval = 100;LRESULT CALLBACK Melter(HWND hWnd, UINT Msg, WPARAM wParam, LPARAM lParam)
{
switch (Msg)
{
case WM_CREATE:
{
HDC Desktop = GetDC(HWND_DESKTOP);
HDC Window = GetDC(hWnd);BitBlt(Window, 0, 0, ScreenWidth, ScreenHeight, Desktop, 0, 0, SRCCOPY);
ReleaseDC(hWnd, Window);
ReleaseDC(HWND_DESKTOP, Desktop);SetTimer(hWnd, 0, Interval, 0);
ShowWindow(hWnd, SW_SHOW);
break;
}
case WM_PAINT:
{
ValidateRect(hWnd, 0);
break;
}
case WM_TIMER:
{
HDC Window = GetDC(hWnd);
int X = (rand() % ScreenWidth) — (150 / 2),
Y = (rand() % 15),
Width = (rand() % 150);
BitBlt(Window, X, Y, Width, ScreenHeight, Window, X, 0, SRCCOPY);
ReleaseDC(hWnd, Window);
break;
}
case WM_DESTROY:
{
KillTimer(hWnd, 0);
PostQuitMessage(0);
break;
}
return 0;
}
return DefWindowProc(hWnd, Msg, wParam, lParam);
}int APIENTRY WinMain(HINSTANCE Inst, HINSTANCE Prev, LPSTR Cmd, int showcmd)
{
// Get the width & height of current display
ScreenWidth = GetSystemMetrics(SM_CXSCREEN);
ScreenHeight = GetSystemMetrics(SM_CYSCREEN);WNDCLASS wndClass = { 0, Melter, 0,0, Inst, 0, LoadCursorW(0, IDC_ARROW), 0, 0, L»ScreenMelter» };
if (RegisterClass(&wndClass))
{
// Create the «melter» overlapping window.
HWND hWnd = CreateWindowExA(WS_EX_TOPMOST, «ScreenMelter», 0, WS_POPUP,
0, 0, ScreenWidth, ScreenHeight, HWND_DESKTOP, 0, Inst, 0);
if (hWnd)
{
// seed for randomization
srand(GetTickCount());
MSG Msg = { 0 };
// Run the melter loop
while (Msg.message != WM_QUIT)
{
if (PeekMessage(&Msg, 0, 0, 0, PM_REMOVE))
{
TranslateMessage(&Msg);
DispatchMessage(&Msg);
}
}
}
}
return 0;
}With many regards, Ben.
-
Edited by
Monday, May 14, 2018 7:46 PM
-
Edited by
Answers
-
If you are creating a project for a window based application, you shouldn’t use the console template.
The console template expects the entry point function to be called main or wmain. If you check the
Visual Studio 2015 documentation, it tells you to use the Win32 Application project type. This project type will expect the WinMain or wWinMain entry point.While you can change it using RLWA32’s suggestion, for future projects it is much easier to use the correct project type.
This is a signature. Any samples given are not meant to have error checking or show best practices. They are meant to just illustrate a point. I may also give inefficient code or introduce some problems to discourage copy/paste coding. This is because
the major point of my posts is to aid in the learning process.-
Marked as answer by
Lxnely
Thursday, May 17, 2018 7:43 PM
-
Marked as answer by
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 |
#include "stdafx.h" #include<iostream> #include<conio.h> #include<string.h> #include<stdio.h> using namespace std; struct mas { char name[20]; char autor[20]; int god; }; class bibl { private: mas kn; public: void in(bibl[], int&); void vyb(bibl[], int&); void poisk(bibl[], int&); void udal(bibl[], int&); void dobavl(bibl[], int&); void vivod(bibl[], int&); }; void clrscr(void) { clrscr(); bibl a[10]; int x = 0; cout << "Vvedite chislo knig:n"; cin >> x; cout << "Vvedite vashi knigi:n"; a[x].in(a, x); _getch(); } void bibl::in(bibl a[], int&x) { for (int i = 0; i<x; i++) { cout << "Nazvanie: "; cin >> a[i].kn.name; cout << "Avtor: "; cin >> a[i].kn.autor; cout << "God izdaniya: "; cin >> a[i].kn.god; } _getch(); clrscr(); a[x].vyb(a, x); } void bibl::vyb(bibl a[], int&x) { int vybor = 0; do { clrscr(); cout << "1-Poisk knign2-udalenye knigin3-dobavlenye knigin4-pokazat bibliotekyn5-vihodnVash vybor:"; cin >> vybor; clrscr(); if (vybor == 1) a[x].poisk(a, x); if (vybor == 2) a[x].udal(a, x); if (vybor == 3) a[x].dobavl(a, x); if (vybor == 4) a[x].vivod(a, x); } while (vybor != 5); } void bibl::poisk(bibl a[], int&x) { int p = 0, god = 0; char name[20], autor[20]; cout << "1-poisk po nazvaniun2-poisk po avtoryn3-poisk po gody izdaniyanVash vibor:"; cin >> p; clrscr(); if (p == 1) { int f = 0; cout << "Vvedite nazvanie: "; cin >> name; for (int i = 0; i<x; i++) { if (strcmp(name, a[i].kn.name) == 0) { cout << a[i].kn.name << " " << a[i].kn.autor << " " << a[i].kn.god << endl; f++; } } if (f == 0) cout << "Net takix knig!"; _getch(); } if (p == 2) { int h = 0; cout << "Vvedite avtora: "; cin >> autor; for (int i = 0; i<x; i++) { if (strcmp(autor, a[i].kn.autor) == 0) { cout << a[i].kn.name << " " << a[i].kn.autor << " " << a[i].kn.god << endl; h++; } } if (h == 0) cout << "Net takix knig!"; _getch(); } if (p == 3) { int g = 0; cout << "Vvedite god izdaniya: "; cin >> god; for (int i = 0; i<x; i++) { if (god == a[i].kn.god) { cout << a[i].kn.name << " " << a[i].kn.autor << " " << a[i].kn.god << endl; g++; } } if (g == 0) cout << "Net takix knig!"; _getch(); } } void bibl::udal(bibl a[], int&x) { int udal; cout << "vvedit adress dlya udaleniya < " << x << endl; cin >> udal; if (x == 1) cout << "udalenye nevozmozhno"; strcpy_s(a[udal - 1].kn.name, a[x - 1].kn.name); strcpy_s(a[udal - 1].kn.autor, a[x - 1].kn.autor); a[udal - 1].kn.god = a[x - 1].kn.god; x--; cout << "Udaleno!n"; } void bibl::dobavl(bibl a[], int&x) { cout << "Nazvanie: "; cin >> a[x].kn.name; cout << "Avtor: "; cin >> a[x].kn.autor; cout << "God izdaniya: "; cin >> a[x].kn.god; x++; } void bibl::vivod(bibl a[], int&x) { for (int i = 0; i<x; i++) { cout << a[i].kn.name << " " << a[i].kn.autor << " " << a[i].kn.god << endl; } _getch(); clrscr(); } |