| 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 |
|
|
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
/VERBOSElinker 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
/EXPORTSand/SYMBOLSoptions 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 get this error, but I don’t know how to fix it.
I’m using Visual Studio 2013. I made the solution name MyProjectTest
This is the structure of my test solution:
—function.h
#ifndef MY_FUNCTION_H
#define MY_FUNCTION_H
int multiple(int x, int y);
#endif
-function.cpp
#include "function.h"
int multiple(int x, int y){
return x*y;
}
—main.cpp
#include <iostream>
#include <cstdlib>
#include "function.h"
using namespace std;
int main(){
int a, b;
cin >> a >> b;
cout << multiple(a, b) << endl;
system("pause");
return 0;
}
I’m a beginner; this is a simple program and it runs without error.
I read on the Internet and became interested in the unit test, so I created a test project:
Menu File → New → Project… → Installed → Templates → Visual C++ → Test → Native Unit Test Project →
Name: UnitTest1
Solution: Add to solution
Then the location auto-switched to the path of the current open solution.
This is the folder structure of the solution:
I only edited file unittest1.cpp:
#include "stdafx.h"
#include "CppUnitTest.h"
#include "../MyProjectTest/function.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestEqual)
{
Assert::AreEqual(multiple(2, 3), 6);
// TODO: Your test code here
}
};
}
But I get:
error LNK2019: unresolved external symbol.
I know that the implementation of function multiple is missing.
I tried to delete the function.cpp file and I replaced the declaration with the definition, and it ran. But writing both declaration and definition in the same file is not recommended.
How can I fix this error without doing that? Should I replace it with #include "../MyProjectTest/function.cpp" in file unittest.cpp?
- Remove From My Forums
-
Вопрос
-
Работаю в с++. (VS 2008)
Встретилась ошибка «LNK2019: ссылка на неразрешенный внешний символ»
Возникает при вызове функции Diagnoz_Database()
Diagnoz DataBase[37]; int D_DataBase=0; void Diagnoz_Redakt(int ¶metr, Diagnoz &Sure); void Diagnoz_Database() { int i, i_while, i_special, p; char *Dolzhnost; system("cls"); fflush(stdin); do{printf("This is a special service menu for editing database diagnosesn"); printf("Choose operationn"); printf("1 - Create new (empty) database (will overwrite)n2 - Loadn3 - Edit an existing databasenESC - exitn"); i_while=_getch(); switch(i_while) { case '1': for(i=0;i<37;i++){DataBase[i].toFile(i);} D_DataBase=1; printf("Press any keyn"); break; case '2': for(i=0;i<37;i++){DataBase[i].fromFile(i);} D_DataBase=1; printf("Press any keyn"); break; if(D_DataBase==1) {case '3': printf("Choose dolzhnost'n"); Dolzhnost=chooseD(p); i_special = p; printf("%S", Dolzhnost); Diagnoz_Redakt(parametr, DataBase[parametr]);} } }while(i_while!=27); } void Diagnoz_Redakt(int ¶metr, Diagnoz &Sure) { int i; printf("You sure? (Y/N)n"); do{ i=_getch(); }while((i!=27) & (i!=110) & (i!=121)); if(i==121) {caseMenu(Sure);} }
Без вызова компилируется нормально. Изменения типа функции, параметров и операторов (switch на if’ы и т.п) ничего не дает. Новых файлов и библиотек после написания функций не подключал. С lib-файлами тоже, вроде бы, все в порядке.
В чем может быть проблема?
Заранее спасибо за ответы.
-
Изменено
25 сентября 2011 г. 15:25
-
Изменен тип
PashaPashModerator
25 сентября 2011 г. 23:10
-
Изменено
Ответы
-
Abolmasov Dmitry
» нужно реализовать функцию void caseMenu(Diagnoz &def), которая просто описана в классе, как дружественная, но реализации ее нет.»
Petalvik
» Одной из причин возникновения LNK2019 является область видимости.»
Вы правы.
Не знаю, является ли это багом моей версии VS, но при наличии более 1000 строк кода между объявлением и реализацией функции возникает ошибка. Решил ее, разбив все большие файлы с кодом на несколько малых.
Всем большое спасибо за помощь.
-
Помечено в качестве ответа
Abolmasov Dmitry
30 сентября 2011 г. 11:23
-
Помечено в качестве ответа
Reported In
Reported In shows products that are verified to work for the solution described in this article. This solution might also apply to other similar products or applications.
Software
- LabWindows/CVI Base
- LabWindows/CVI Full
- Microsoft Visual Studio
Other
Microsoft Visual Studio
Issue Details
I am trying to use LabWindows/CVI functions in my Visual Studio C++ project, but when I try to compile my code I receive linking errors similar to the following:
error LNK2019: unresolved external symbol
Solution
In order to compile LabWindows/CVI functions in a Visual Studio C++ program, you first have to build the functions into a dynamic-link library (.dll) with an import library, and then link the import library (.lib) to your C++ project. To build the functions into a DLL and resolve the link errors, complete the following steps:
- If the instrument driver that includes the functions is not already loaded into LabWindows/CVI, you will need to load it by going to Instrument>>Load. In the dialog box that opens, navigate to the .fp file of interest and click Load.
- Open the Function Tree Editor by going to File>>Open>>Function Tree (*.fp). In the dialog box that opens, navigate to the .fp file of interest and click Load.
- Create a DLL project by going to Options>>Create DLL Project. Specify a path and name for your project and click Save. A message will pop up asking you if you want to load the DLL project now, similar to the dialog below. Click Yes.
- Before building the DLL, you will need to configure some of the build settings. First set the build target type by going to Build>>Target Type and making sure there is a checkmark next to Dynamic Link Library. Also set the project to release mode by going to Build>>Configuration and ensuring there is a checkmark next to Release.
- Go to Build>>Target Settings and change the following settings:
- Change the Run-time support option to Full run-time engine, as shown in the image below
- Change the type library settings by clicking Type Library and unchecking Add type library resource to DLL. If you do not uncheck this option, you may run into a type definition error when attempting to build, similar to Definitions for these types could not be found.
Then click OK to exit out of both windows.
- Build the DLL. In LabWindows/CVI 2012 or earlier, select Build>>Create Release Dynamic Link Library. In LabWindows/CVI 2013, select Build>>Build. This will create a dynamic-link library (.dll) and an import library (.lib) containing the LabWindows/CVI functions you are trying to use. We can now link the import library to the Visual Studio project.
- Open your Visual Studio C++ project, and go to Project>>Properties. In the Properties window, go to Configuration Properties>>C/C++>>General. Click the Additional Include Directories field. Then click the arrow that appears and select <Edit…>.
- In the dialog box that opens, click the New Line button, add the directory that contains the header file and click OK.
- Navigate to Configuration Properties>>Linker>>Input. Click the Additional Dependencies field and then click the arrow that appears and select <Edit…>.
- In the dialog box that opens, add the path of the import library to the list of Additional Dependencies.
- Compile your Visual Studio project, and the linking errors should be resolved. If you are still seeing linking errors, it may be that your project is dependent upon more than one library of LabWindows/CVI functions. In this case, you will want to repeat these steps for the other libraries.
Additional Information
If the functions you are trying to use are already bundled into a DLL with an import library, you can skip steps 1 through 6.
If you still has a link error, it is most probably due to name mangling issue. The C++ language allows you to overide some functions (such as methods in Object Oriented Programming). To resolve some names conflits, the C++ compiler add name mangling in order to have a unique name indentifier.
So when you call a C library in C++ programm, the C++ compiler needs to know that it do not need to modify the name. If it is the case, the name created by the C++ compiler is different from what is in your C code, and explain the linkage error.
In order to solve it, you need to add the following code in the header file (.h) related to you .c file.
#ifdef __cplusplus
extern "C" {
#endif
/* The functions you want to keep the same in C and C++ */
#ifdef __cplusplus
}
#endif
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 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 |
#pragma once #undef main #define _CRT_SECURE_NO_WARNINGS #include "lab_1 header.h" #include <iostream> #include <stdlib.h> #include <string.h> #include <cmath> using namespace std; int main(void) //int main(void) { system("chcp 1251 > nul"); system("PAUSE"); char SW; MENU:; system("CLS"); MENU2:; cout << "4.1 - 1. Создать в VS консольный проект" << endl; cout << "4.2 - 2. Обеспечить русификацию консольного ввода и вывода" << endl; cout << "4.3 - 3. Вариант для выполнения заданий ЛР" << endl; cout << "4.4 - 4. Описание переменных и массивов" << endl; cout << "4.5 - 5. Указатели и ссылки" << endl; cout << "4.6 - 6. Структуры данных" << endl; cout << "4.7 - 7. Динамическая память для структурных переменных и массива структур" << endl; cout << "4.8 - 8. Циклы и операторы ветвления" << endl; cout << "4.9 - 9. Описание функции и ее вызов" << endl; cout << "y - Выход" << endl; cout << "0 - Меню" << endl; cout << "Выберите пункт меню: n" << endl; SW = getchar(); switch (SW) { case '1': { cout << "Выбор №1" << endl; cout << "4.1 - Проверка создания консольного проекта" << endl; system("PAUSE"); SW = getchar(); goto MENU; break; } case '2': { cout << "Выбор №2" << endl; cout << "4.2 - Обеспечить руссификацию консольного ввода и вывода" << endl; cout << "Обеспечение руссификации" << endl; system("PAUSE"); SW = getchar(); goto MENU; break; } case '3': { cout << "Выбор №3" << endl; cout << "4.3 - Показать вариант для выполнения задании ЛР" << endl; cout << "Вариант для выполнения задании лабораторной работы №1 - 2 вариант" << endl; system("PAUSE"); SW = getchar(); goto MENU; break; } case '4': { cout << "Выбор №4" << endl; cout << "4.4 - Выполнить описание переменных и массивов n" << endl; cout << "Описание переменных и массивов" << endl; // Переменные разных типов int iVar = 10; long lVar = 29; char cVar = 's'; float fVar = 1.99f; double dVar = 99.099; cout << "iVar = " << iVar << 'n' << endl; cout << "lVar = " << lVar << 'n' << endl; cout << "cVar = " << cVar << 'n' << endl; cout << "fVar = " << fVar << 'n' << endl; cout << "dVar = " << dVar << 'n' << endl; // Массивы разных типов int iMas[2][4] = { {3,4,5,6},{5,6,7,8} }; char cMas[1][40] = { "Абракадабра" }; float fMas[2] = { 99.9f, 66.6f }; cout << "Описание массивов: " << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << "iMas = [" << i << "]" << "[" << j << "]" << iMas[i][j] << endl; // i, j - индексы элемента в массиве } } cout << 'n'; cout << "До изменения элемента массива" << 'n'; for (int i = 0; i < 2; i++) cout << "fMas = [" << i << "]" << fMas[i] << endl; // i - индекс элемента в массиве fMas[1] = 77.11f; cout << "После изменения элемента массива" << 'n'; for (int i = 0; i < 2; i++) cout << "fMas = [" << i << "]" << fMas[i] << endl; system("PAUSE"); SW = getchar(); goto MENU; break; } case '5': { cout << "Выбор №5" << endl; cout << "4.5 - Указатели и ссылки" << endl; cout << "Указатели на переменные" << "n" << endl; int iVal = 5; //простая переменная int* pInt = &iVal; //указатель на переменную типа int и присваивание адреса переменной iVal cout << "До изменения значения: " << 'n' << endl; cout << "Адрес указателя pInt = " << pInt << 'n' << endl; cout << "Адрес переменной iVal = " << &iVal << 'n' << endl; *pInt = *pInt * 2; cout << "После изменения значения: " << "n" << endl; cout << "Адрес указателя pInt = " << pInt << "n" << endl; cout << "Адрес переменной iVal = " << &iVal << "n" << endl; cout << "Ссылки на переменные" << "n" << endl; int& rInt = iVal; iVal = 15; cout << "До изменения значения: " << 'n' << endl; cout << "Ссылка rInt = " << &rInt << 'n' << endl; cout << "Ссылка iVal = " << iVal << 'n' << endl; rInt = rInt - 5; cout << "После изменения значения: " << "n" << endl; cout << "Ссылка rInt = " << &rInt << "n" << endl; cout << "Ссылка iVal = " << iVal << "n" << endl; cout << "Указатели на функции" << "n" << endl; //не понял как работает fun1(4, 8); //вызов функции суммы fun2(4, 8); //вызов функции разности int result; int(*pFun)(int, int); //указатель на функцию с возвратом 2 типов (int,int) pFun = fun1; cout << "Вычисление через указатель" << "n" << endl; result = pFun(55, 66); cout << pFun(55, 66) << endl; system("PAUSE"); SW = getchar(); goto MENU; break; } //case '6': //{ // cout << "Выбор №6" << endl; // cout << "4.6 - Структуры данных" << 'n' << endl; // struct Kaf K1 = { "ИУ-1", 1, 12, 6307.33f }; // printKaf(K1); // struct Kaf K0; // = { "", 0, 0, 0.0f }; // printKaf(K0); // strcpy_s(K0.name, "ИУ-6"); // K0.year = 3; //3.0f // K0.howmany = 9; // K0.grants = 5908.88f; // printKaf(K0); // Kaf Faculty[] = { {"ИУ-9", 3, 10, 7707.22f}, {"ИУ-4", 2, 13, 5797.11f} }; // //распечатка массива структур // for (int i = 0; i < sizeof(Faculty) / sizeof(Kaf); i++) // printArrayKaf(Faculty, sizeof(Faculty) / sizeof(Kaf)); // system("PASUE"); // SW = getchar(); // goto MENU; // break; // //} case '7': { cout << "Выбор №7!" << endl; cout << "4.7 - Динамическая память для структурных переменных и массива структур" << endl; int* pdInt; pdInt = new int; *pdInt = 25; cout << endl << "pdInt [" << pdInt << "]: " << *pdInt << endl; delete pdInt; Kaf* pdKaf = new Kaf; strcpy_s(pdKaf->name, "ИУ-7"); pdKaf->year = 4; pdKaf->howmany = 18; pdKaf->grants = 3008, 21; cout << "Указатель pdKaf: [" << pdKaf << "]" << endl; printKaf(*pdKaf); delete pdKaf; Kaf* pdK = new Kaf[3]; strcpy_s(pdK[0].name, "ИУ-4"); pdK[0].year = 3; pdK[0].howmany = 18; pdK[0].grants = 4500.31f; strcpy_s(pdK[1].name, "ИУ-9"); pdK[1].year = 5; pdK[1].howmany = 28; pdK[1].grants = 4200.01f; strcpy_s(pdK[2].name, "ИУ-8"); pdK[2].year = 4; pdK[2].howmany = 19; pdK[2].grants = 6500.8f; cout << "Распечатка динамического массива pdK:" << endl; // Распечатка массива структур for (int i = 0; i < 3; i++) cout << "n" << endl << "Название кафедры: " << pdK[i].name << endl << "Кол-во лет обучения = " << pdK[i].year << endl << "Кол-во студентов = " << pdK[i].howmany << endl << "Размер стипендии = " << pdK[i].grants << endl << "n" << endl; delete[]pdK; system("PAUSE"); SW = getchar(); // Сброс ENTER goto MENU; break; } case '8': { cout << "Выбор №8!" << endl; cout << "4.8 - Циклы и операторы ветвления" << endl; int Razm = 5; int* pMas = new int[Razm]; pMas[0] = 3; pMas[1] = 2112; pMas[2] = 61; pMas[3] = 32; pMas[4] = 213; cout << "Распечатка массива: " << endl; for (int i = 0; i < Razm; i++) cout << " [" << i << "] = " << pMas[i] << endl; // Сортировка for (int k = 0; k < (Razm - 1); k++) { for (int i = 0; i < (Razm - 1); i++) { if (pMas[i] <= pMas[i + 1]) // Убывание { // Swap int Temp; Temp = pMas[i]; pMas[i] = pMas[i + 1]; pMas[i + 1] = Temp; }; }; }; cout << "Распечатка отсортированного массива: " << endl; for (int i = 0; i < Razm; i++) cout << " [" << i << "] = " << pMas[i] << endl; delete[]pMas; system("PAUSE"); SW = getchar(); // Сброс ENTER goto MENU; break; } case '9': { cout << "Выбор №9!" << endl; cout << "4.9 - Описание функции и ее вызов" << endl; cout << "Простая функция" << 'n' << endl; float fMas[3] = { 44.5f, 11.44f, 98.3f }; for (int i = 0; i < 3; i++) cout << "[" << i << "] = " << fMas[i] << endl; Multy(fMas, sizeof(fMas) / sizeof(float)); cout << "Multy = " << Multy << endl; cout << "Функция сортировки" << 'n' << endl; cout << "До сортировки: " << endl; int Mas[3] = { 11, 32, 9 }; cout << " " << endl; for (int i = 0; i < 3; i++) cout << " [" << i << "] = " << Mas[i] << endl; //int size = sizeof(Mas) / sizeof(int); //SortMas(Mas, size); Kaf* pdK = new Kaf[3]; Kaf Faculty[] = { {"IU-1", 4, 26, 3670.32f}, {"IU-5", 4, 29, 2867.5f}, {"IU-7", 5, 22, 2902.2f} }; printArrayKaf(Faculty, 3); // Распечатка массива структур for (int k = 0; k < 3; k++) for (int i = 0; i < 3; i++) if ((Faculty + i)->howmany < (Faculty + i + 1)->howmany) // Убывание SwapKaf(Faculty + i, Faculty + i + 1); printArrayKaf(Faculty, 3); Sort(Faculty); cout << "После сортировки" << endl; SortMas(Mas, 3); cout << " " << endl; for (int i = 0; i < 3; i++) cout << " [" << i << "] = " << Mas[i] << endl; // Распечатка массива структур printArrayKaf(Faculty, 3); system("PAUSE"); SW = getchar(); // Сброс ENTER goto MENU; break; } }; system("PAUSE"); } |


