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?
Because of the comment below, I’ve rewritten what I had before.
The problem that the linker is complaining about is that you’ve declared your member functions in Poker
, but haven’t defined them. How is this? For starters, you’re creating a new class and defining separate member functions in it.
Your header file Poker
class exists in the PokerGame
namespace and your cpp file Poker
class exists in the global namespace. To fix that issue, put them in the same namespace:
//cpp file
namespace PokerGame {
class Poker {
...
};
}
Now that they’re in the same namespace, you have another issue. You’re defining your member functions inside the class body, but not the first one. The definitions simply can’t go in the body of a class named the same way. Get rid of the whole class in the cpp file:
//cpp file
namespace PokerGame {
Poker::Poker() {
deck = Deck(); //consider a member initializer instead
}
//other definitions
}
One last thing: you put the private section of your class in the wrong spot. It was in that cpp file class that we just removed. It belongs with the other parts of your class:
//header file
namespace PokerGame {
class Poker {
public:
//public stuff
private:
Deck deck; //moved from cpp file
};
}
Как решить проблему?
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_DeleteGrammarEngine(void *)» (?sol_DeleteGrammarEngine@@YGHPAX@Z) в функции _main
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_CountEntries(void *)» (?sol_CountEntries@@YGHPAX@Z) в функции _main
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «void * __stdcall sol_CreateGrammarEngineW(wchar_t const *)» (?sol_CreateGrammarEngineW@@YGPAXPB_W@Z) в функции _main
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_FindEntry(void *,wchar_t const *,int,int)» (?sol_FindEntry@@YGHPAXPB_WHH@Z) в функции «void __cdecl TestRussian(void *)» (?TestRussian@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_DeletePhraseGenerator(void *)» (?sol_DeletePhraseGenerator@@YGHPAX@Z) в функции «void __cdecl TestEnglish(void *)» (?TestEnglish@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_DeleteGeneratedPhrase(wchar_t *)» (?sol_DeleteGeneratedPhrase@@YGHPA_W@Z) в функции «void __cdecl TestEnglish(void *)» (?TestEnglish@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «wchar_t * __stdcall sol_GeneratePhrase(void *,int,int)» (?sol_GeneratePhrase@@YGPA_WPAXHH@Z) в функции «void __cdecl TestEnglish(void *)» (?TestEnglish@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_Paraphrase(void *,int,int,int,int,int,int,int,wchar_t const *,wchar_t *,int,int)» (?sol_Paraphrase@@YGHPAXHHHHHHHPB_WPA_WHH@Z) в функции «void __cdecl TestEnglish(void *)»
(?TestEnglish@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_GetVersion(void *,int *,int *,int *)» (?sol_GetVersion@@YGHPAXPAH11@Z) в функции «void __cdecl TestEnglish(void *)» (?TestEnglish@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «void * __stdcall sol_CreatePhraseGenerator(void *,int)» (?sol_CreatePhraseGenerator@@YGPAXPAXH@Z) в функции «void __cdecl TestEnglish(void *)» (?TestEnglish@@YAXPAX@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_MatchNGrams(void *,wchar_t const *,int *,int *,int *)» (?sol_MatchNGrams@@YGHPAXPB_WPAH22@Z) в функции «void __cdecl Imitate(wchar_t const *,int)» (?Imitate@@YAXPB_WH@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_LoadKnowledgeBase(void *,wchar_t const *)» (?sol_LoadKnowledgeBase@@YGHPAXPB_W@Z) в функции «void __cdecl Imitate(wchar_t const *,int)» (?Imitate@@YAXPB_WH@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_BuildKnowledgeBase(void *,wchar_t const *,wchar_t const *,int,int)» (?sol_BuildKnowledgeBase@@YGHPAXPB_W1HH@Z) в функции «void __cdecl Imitate(wchar_t const *,int)» (?Imitate@@YAXPB_WH@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_BuildKnowledgeBase2(void *,wchar_t const *,int,int)» (?sol_BuildKnowledgeBase2@@YGHPAXPB_WHH@Z) в функции «void __cdecl Imitate(wchar_t const *,int)» (?Imitate@@YAXPB_WH@Z)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_Set2GramsForPhrase(void *,int,int const *)» (?sol_Set2GramsForPhrase@@YGHPAXHPBH@Z) в функции «void __cdecl TestGenerator(void)» (?TestGenerator@@YAXXZ)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_SetWordsForPhrase(void *,int,int const *,int)» (?sol_SetWordsForPhrase@@YGHPAXHPBHH@Z) в функции «void __cdecl TestGenerator(void)» (?TestGenerator@@YAXXZ)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_StopSynonyms(void *,int,int const *,int)» (?sol_StopSynonyms@@YGHPAXHPBHH@Z) в функции «void __cdecl TestSynonymizer(void)» (?TestSynonymizer@@YAXXZ)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «void __stdcall sol_DeleteProjections(void *)» (?sol_DeleteProjections@@YGXPAX@Z) в функции «void __cdecl TestSynonymizer(void)» (?TestSynonymizer@@YAXXZ)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «int __stdcall sol_GetIEntry(void *,int)» (?sol_GetIEntry@@YGHPAXH@Z) в функции «void __cdecl TestSynonymizer(void)» (?TestSynonymizer@@YAXXZ)
1>fff.obj : error LNK2019: ссылка на неразрешенный внешний символ «void * __stdcall sol_ProjectWord(void *,wchar_t const *,int)» (?sol_ProjectWord@@YGPAXPAXPB_WH@Z) в функции «void __cdecl TestSynonymizer(void)» (?TestSynonymizer@@YAXXZ)
1>C:\Users\111\Desktop\fff\Debug\fff.exe : fatal error LNK1120: 20 неразрешенных внешних элементов
Вот текст программы:
#include «StdAfx.h»
#include <iostream>
#include <vector>
#include <tchar.h>
#include <windows.h>
#include <process.h>
#include <assert.h>
// Grammar Engine API
// API грамматической машины
#include <D:\Program Files (x86)\SynonymizerSDK\include\lem\solarix\synonymizer_engine.h>
#include <D:\Program Files (x86)\SynonymizerSDK\include\lem\solarix\_sg_api.h>
using namespace std;
void TestRussian( HFAIND hEngine );
void TestEnglish( HFAIND hEngine );
const int DEF_TIMEOUT = 1000000; // 1000 секунд
static bool exists( const TCHAR *path )
{ return GetFileAttributes(path)!=(DWORD)INVALID_FILE_ATTRIBUTES; }
// **************************************************************
// Вспомогательная процедура — вывод UNICODE текста на консоль
// **************************************************************
static void wide( const wchar_t *ustr )
{
if( ustr==NULL || *ustr==0 )
return;
const int l = wcslen(ustr);
char *abuffer = new char[l+1];
memset( abuffer, 0, l+1 );
WideCharToMultiByte( CP_OEMCP, 0, ustr, l+1, abuffer, l+1, NULL, NULL );
printf( «%s», abuffer );
delete[] abuffer;
return;
}
static HFAIND hEngine = NULL;
static HGREN_PHRASOMAT hFG = NULL;
#if defined TEST_THREADS
unsigned int __stdcall FG_Thread(void*)
{
const wchar_t *words[] = {
L»ПОЛУНОЧИ»,
NULL
};
std::vector<int> ies;
int j=0;
while( words[j]!=NULL )
{
int ie = sol_FindEntry( hEngine, words[j++], NOUN_ru, -1 );
if( ie!=-1 )
ies.push_back(ie);
}
sol_SetWordsForPhrase( hFG, ies.size(), &*ies.begin(), true );
// Сгенерируем парочку предложений с измененным набором слов
for( int i=0; i<1000; i++ )
{
wchar_t *phrase = sol_GeneratePhrase(hFG,0xffffffff,FG_DEBUG);
printf( «#%5d—>», i );
wide(phrase);
printf( «\n» );
sol_DeleteGeneratedPhrase(phrase);
}
return 0;
}
#endif
static void Imitate( const wchar_t *src_filename, int language )
{
if( GetFileAttributesW(src_filename)==(DWORD)-1 )
{
return;
}
// генерация квазислучайного текста на основе сведений о матрице переходов,
// создаваемой по исходному тексту.
// Сначала строим матрицу.
int rc1 = sol_BuildKnowledgeBase2( hFG, L»e:\\MVoice\\lem\\scripts\\rewriter\\путеводитель.txt», 3, 0 );
// Теперь генерация текста.
for( int i=0; i<20; i++ )
{
wchar_t *phrase = sol_GeneratePhrase(
hFG,
FG_GENERATOR_USES_CHAINS,
FG_NO_DEBUG
);
printf( «#%2d «, i );
wide(phrase);
printf( «\n» );
sol_DeleteGeneratedPhrase(phrase);
}
// ——————————————————————
// Имитация стиля — строим базу знаний из текста и затем генерируем
// случайный текст на основе информации.
// ——————————————————————
wchar_t tmp_db_folder[MAX_PATH];
swprintf( tmp_db_folder, L»%s\\TestKnowledgeBase», _wgetenv(L»TMP») );
CreateDirectoryW( tmp_db_folder, NULL );
// удалим старое содержимое, если оно было.
wchar_t cmdx[MAX_PATH*2];
swprintf( cmdx, L»del /q %s\\*.*», tmp_db_folder );
_wsystem( cmdx );
int rc = sol_BuildKnowledgeBase( hEngine, src_filename, tmp_db_folder, language, 0 );
rc = sol_LoadKnowledgeBase( hFG, tmp_db_folder );
for( int i=0; i<20; i++ )
{
wchar_t *phrase = sol_GeneratePhrase(
hFG,
FG_LOGICS | FG_GERUND1
| FG_GERUND2 | FG_COMSENT |
FG_USE_LEX_WHEN_EXHAUSTED
|
FG_DONT_REMOVE_USED |
FG_GENERATOR_USES_NGRAMS,
FG_DEBUG
);
// рассчитываем оценку достоверности фразы по стистическому критерию
int unmatched_2_ngrams=0, n2=0, n3=0;
int rc = sol_MatchNGrams( hEngine, phrase, &unmatched_2_ngrams, &n2, &n3 );
float r=0.0F;
if( (n2+unmatched_2_ngrams)!=0 )
r = float(n2+n3)/float(n2+n3+unmatched_2_ngrams);
printf( «#%2d «, i );
wide(phrase);
printf( » [[%g]]\n», r );
sol_DeleteGeneratedPhrase(phrase);
}
return;
}
int main(void)
{
// Грузим морфологию, синтаксис и другие модули.
// Словарь должен быть уже подготовлен и находится в текущем каталоге или одном
// из стандартных для SDK/Integra каталогов. Для подготовки словаря можно запустить
// один из скриптов в \sdk\scripts\dictionary.
cout << «Loading grammar engine…\n»;
bool dict_ok=false;
const TCHAR * paths[] = {
_T(«..\\..\\..\\..\\..\\..\\bin-windows\\dictionary.xml»),
_T(«..\\..\\..\\..\\..\\..\\dictionary.xml»),
_T(«dictionary.xml»),
NULL
};
int ipath=0;
while( paths[ipath]!=NULL && dict_ok==false )
{
if( exists(paths[ipath]) )
{
hEngine = sol_CreateGrammarEngine(paths[ipath++]);
if( hEngine!=NULL )
dict_ok=true;
}
}
if( dict_ok )
{
int nentry = sol_CountEntries(hEngine);
cout << «Engine is loaded OK\n»;
}
else
{
cout << «Error loading dictionary file ‘diction.xml\n»
«You have to download the latest dictionary build\n»
«from http://sourceforge.net/project/solarix»;
return -1;
}
TestRussian(hEngine);
//TestEnglish(hEngine);
// Free allocated resources, delete the engine instance.
sol_DeleteGrammarEngine(hEngine);
cout << «All done.\n»;
return 0;
}
static void TestGenerator(void);
static void TestSynonymizer(void);
static void TestParaphraser(void);
static void TestImitator(void);
void TestRussian( HFAIND hEngine )
{
if( sol_FindEntry( hEngine, L»МАМА», /*Solarix::API::*/NOUN_ru, /*Solarix::API::*/RUSSIAN_LANGUAGE )==-1 )
{
cout << «Russian lexicon is missing.\n»;
return;
}
TestGenerator();
TestSynonymizer();
// TestParaphraser();
TestImitator();
return;
}
void TestEnglish( HFAIND hEngine )
{
// Проверяем наличие английского лексикона.
if( sol_FindEntry( hEngine, L»MOTHER», /*Solarix::API::*/NOUN_en, /*Solarix::API::*/ENGLISH_LANGUAGE )==-1 )
{
cout << «English lexicon is missing.\n»;
return;
}
// Создаем генератор предложений для английского языка
hFG = sol_CreatePhraseGenerator(hEngine,ENGLISH_LANGUAGE);
wchar_t buffer[10001];
memset( buffer, 0, sizeof(buffer) );
bool is_premium = sol_GetVersion( hEngine, NULL, NULL, NULL);
if( is_premium )
{
// Проверяем сложные синонимы (доступно в версии Premium)
const wchar_t *orgs[] =
{
L»I decided to stay»,
L»I’ve decided to stay»,
L»We decide to stay»,
L»He decides to stay»,
L»I am deciding to stay»,
L»You must decide to stay»,
NULL
};
int iorg=0;
while( orgs[iorg]!=NULL )
{
const wchar_t *s = orgs[iorg];
int rc2 = sol_Paraphrase(
hFG,
FG_SYNONYMIZE | FG_SYNONYMIZER_MULTIWORD,
FG_PEDANTIC_ANALYSIS,
FG_NO_NGRAMS,
0,
FG_DEBUG,
FG_YIELD_PLAIN_TEXT,
5,
s,
buffer,
10000,
DEF_TIMEOUT
);
printf( «%s —> «, s );
wide(buffer);
printf( «\n» );
iorg++;
}
}
// int rc = sol_Paraphrase( hFG, FG_SYNONYMIZE_OTHERS | FG_SYNONYMIZER_USES_NGRAMS | FG_DEBUG, 5, L»The cat catches the mouse.», buffer, 10000 );
const wchar_t *orgs[] =
{
L»I decided to stay»,
L»The mouse will be surrendering»,
L»The mouse is surrendering»,
L»The jolly mouse», // тут ошибка!
L»The funny mouse»,
L»The mouse surrendered»,
L»is asked»,
L»will be asked»,
L»will be asking»,
L»will be surrendering»,
L»is surrendering»,
L»The mouse surrenders»,
L»The mouse will surrender»,
L»Kitties»,
L»Funny job»,
L»Merry christmas»,
L»Tremendous danger»,
L»Huge disaster»,
L»The mouse gives up.»,
L»The kitty surrendered.»,
L»White cat silently sleeps.»,
L»Black cat catches the moise.»,
NULL
};
int iorg=0;
while( orgs[iorg]!=NULL )
{
const wchar_t *s = orgs[iorg];
int rc = sol_Paraphrase(
hFG,
FG_SYNONYMIZE | FG_SYNONYMIZER_MULTIWORD,
FG_PEDANTIC_ANALYSIS,
FG_NO_NGRAMS,
0,
FG_DEBUG,
FG_YIELD_PLAIN_TEXT,
5,
s,
buffer,
10000,
DEF_TIMEOUT
);
if( wcscmp( s, buffer )==0 )
{
printf( «Error, no synonymization occured for phrase: %s\n», s );
}
else
{
printf( «#%d «, iorg );
wide(s);
printf( » —> » );
wide(buffer);
printf( «\n» );
}
iorg++;
}
// sol_RandomizePhraseGenerator(hFG);
// Тестируем нефильтрованную по лексике генерацию
for( int i=0; i<30; i++ )
{
wchar_t *phrase = sol_GeneratePhrase(hFG,0,FG_DEBUG);
if( wcsstr( phrase, L»(—» )!=NULL || wcsstr( phrase, L»???» )!=NULL )
{
printf( «Error in phrase generator!\n» );
}
printf( «#%2d «, i );
wide(phrase);
printf( «\n» );
sol_DeleteGeneratedPhrase(phrase);
}
Imitate( L»..\\..\\..\\..\\..\\..\\scripts\\rewriter\\etalons-en.txt», ENGLISH_LANGUAGE );
sol_DeletePhraseGenerator(hFG);
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"); } |
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and
privacy statement. We’ll occasionally send you account related emails.
Already on GitHub?
Sign in
to your account
Assignees
Comments
Error Obtained
Getting linker error LNK2019 when linking boost libraries.
Environment
- OS: Win10 Pro build 1809
- Compiler: Visual studio 2019 (v142), C++ 14
To Reproduce
Steps to reproduce the behavior:
See the attached cmakelists.txt for the makelist that I used to see this issue.
Expected behavior
Build with no errors
Failure logs
2>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) bool __cdecl boost::this_thread::interruptible_wait(void *,struct boost::detail::mono_platform_timepoint const &)" (__imp_?interruptible_wait@this_thread@boost@@YA_NPEAXAEBUmono_platform_timepoint@detail@2@@Z) referenced in function "void __cdecl boost::this_thread::sleep_for<__int64,class boost::ratio<1,1> >(class boost::chrono::duration<__int64,class boost::ratio<1,1> > const &)" (??$sleep_for@_JV?$ratio@$00$00@boost@@@this_thread@boost@@YAXAEBV?$duration@_JV?$ratio@$00$00@boost@@@chrono@1@@Z)
2>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) private: void __cdecl boost::thread::start_thread(void)" (__imp_?start_thread@thread@boost@@AEAAXXZ) referenced in function main
2>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) private: static class boost::intrusive_ptr<struct boost::detail::thread_data_base> __cdecl boost::thread::make_thread_info(void (__cdecl*)(void))" (__imp_?make_thread_info@thread@boost@@CA?AV?$intrusive_ptr@Uthread_data_base@detail@boost@@@2@P6AXXZ@Z) referenced in function main
2>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: __cdecl boost::thread::~thread(void)" (__imp_??1thread@boost@@QEAA@XZ) referenced in function main
2>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) public: void __cdecl boost::thread::join(void)" (__imp_?join@thread@boost@@QEAAXXZ) referenced in function main
2>main.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) class boost::thread::id __cdecl boost::this_thread::get_id(void)" (__imp_?get_id@this_thread@boost@@YA?AVid@thread@2@XZ) referenced in function "void __cdecl thread(void)" (?thread@@YAXXZ)
2>main.obj : error LNK2001: unresolved external symbol "public: __cdecl boost::thread::~thread(void)" (??1thread@boost@@QEAA@XZ)
2>E:\repos\boost-test\build2019\Release\Example.exe : fatal error LNK1120: 7 unresolved externals
CMakeLists.txt
@JackBoosY this is not a port bug, question was better
@aditya369007 your CMakeLists is not the best example of boost usage with cmake. In any case you are missing a reference to boost-thread library to link
Hi @aditya369007, you can use find_package(Boost REQUIRED COMPONENTS <...>)
to find boost libraries and include path using vcpkg tool-chain(command .\vcpkg integrate install
).
The following cmake code is correct:
# CMakeList.txt : CMake project for CMakeProject10, include source and define
# project specific logic here.
#
cmake_minimum_required (VERSION 3.8)
# Add source to this project's executable.
add_executable (CMakeProject10 "CMakeProject10.cpp" "CMakeProject10.h")
# TODO: Add tests and install targets if needed.
set(CMAKE_CXX_STANDARD 14)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
set(CMAKE_CXX_EXTENSIONS OFF)
if(CMAKE_CXX_FLAGS MATCHES "/W[0-4]")
string(REGEX REPLACE "/W[0-4]" "/W4" CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS}")
endif()
find_package(Boost REQUIRED COMPONENTS thread)
include_directories(${Boost_INCLUDE_DIRS})
target_link_libraries(CMakeProject10 ${Boost_LIBRARIES})
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang|AppleClang|GNU")
target_compile_options(CMakeProject10 PRIVATE -Wall -Wextra -Wunreachable-code -Wpedantic)
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "Clang")
target_compile_options(CMakeProject10 PRIVATE -Wweak-vtables -Wexit-time-destructors -Wglobal-constructors -Wmissing-noreturn )
endif()
if (CMAKE_CXX_COMPILER_ID MATCHES "MSVC")
target_compile_options(CMakeProject10 PRIVATE /W4 /w44265 /w44061 /w44062 )
endif()
Thanks.
@LilyWangL the find_package(Boost REQUIRED COMPONENTS thread)
did the trick. Works like a charm. Thank you!