What does 'Error LNK2019: unresolved external symbol' mean? - c++

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 2\well-formed expression checker solution\well-formed expression checker project\main.cpp(11): warning C4101: 'n' : unreferenced local variable
1>e:\c++ language 2\well-formed expression checker solution\well-formed expression checker project\main.cpp(11): warning C4101: 'N' : unreferenced local variable
1>e:\c++ language 2\well-formed expression checker solution\well-formed expression checker project\main.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 2\Well-Form ed Expression Checker Solution\Debug\Well-Formed Expression Checker Project.exe : fatal error LNK1120: 2 unresolved externals
Thanks for the help.

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.

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.

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.

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).

Remove the lines:
char n, N;
StackLS stack;
and see how you go.

Related

Linker error when compiling STL container vector in Solaris Platform

I am trying to use C++ STL container vector on a Solaris platform but I am unable to compile it successfully. I am getting the following error:
Undefined first referenced symbol in file
void std::vector<int>::__insert_aux(int*,const int&) iqdir_r_o/st_database.o
ld: fatal: symbol referencing errors.
No output written to libiq16.so.1
Error:Link failed with exit code 512.
Here is the piece of code I have added:
void st_database::cpp_stl_vector_test(){
std::cout << "Entering Vector Test\n";
std::cout << "--------------------\n";
std::vector<int> vec;
vec.push_back(10);
vec.push_back(20);
std::cout << "Exiting Vector Test\n";
std::cout << "-------------------\n";
}
I have also included the vector header file.

"Duplicate symbol" when attempting to compile two .cpp files (from XCode) in terminal (MacOSX)

I have two .cpp files, main.cpp and secondFile.cpp:
#include <iostream>
int main()
{
std::cout << "Hello, World!\n" << std::endl;
std::cout << "I was also able to add this line!" << std::endl;
return 0;
}
And
#include <iostream>
int main()
{
std::cout << "This was from the second file!" << std::endl;
return 0;
}
I have successfully run g++ -o main.cpp main and g++ -o secondFile.cpp secondFile, as well as run each of their corresponding executables. However when I attempt to compile them simultaneously into a single executable g++ -o main.cpp secondFile.cpp bothScripts or clang++ main.cpp secondFile.cpp -o bothScripts I receive the following error:
"duplicate symbol _main in:
/var/folders/49/38grlkzs44zcth3v_dw9m9dm0000gn/T/main-d43536.o
/var/folders/49/38grlkzs44zcth3v_dw9m9dm0000gn/T/secondfile-2bee63.o
ld: 1 duplicate symbol for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)"
Clearly something is being loaded twice, but I am unsure whether this is a library (iostream), that I've named both sections 'main', or something else entirely. There are certainly questions similar to this already, but many are convoluted and not as fundamental for new C++ members (hence my question here).
Context: My rationale is to practice building executables from multiple .cpp files. Is there a better way to go about this? (New to C++ but not to programming/code as a whole.)
The reason for your error is simple. You have 2 main() functions. As you should know, in a C++ program, the function main() generally defines the entry point of a program. When each of the files are compiled together, and have their own main() function, the compiler gets confused and throws an error. To solve this, simply change the name of the main() function in one file, and call it from the other file, if you are planning to run them together.

Linker error building fibonnacci example with boost::coroutine2 with Boost 1.60 using Dynamic Linking

I have made a simple project in visual studio 2015 to reproduce an issue I'm having in a larger codebase with Boost 1.60
I have tried to simply compile and run a sample found here: https://github.com/boostorg/coroutine2/blob/develop/example/fibonacci.cpp
with 1 slight change - to use dynamic libraries.
Thus, my full code is as follows:
#include <cstdlib>
#include <iostream>
#define BOOST_ALL_DYN_LINK //This is the only difference
#include <boost/coroutine2/all.hpp>
int main() {
boost::coroutines2::coroutine< int >::pull_type source(
[](boost::coroutines2::coroutine< int >::push_type & sink) {
int first = 1, second = 1;
sink(first);
sink(second);
for (int i = 0; i < 8; ++i) {
int third = first + second;
first = second;
second = third;
sink(third);
}
});
for (auto i : source) {
std::cout << i << " ";
}
std::cout << "\nDone" << std::endl;
return EXIT_SUCCESS;
}
However, I am getting a linker error:
1>------ Build started: Project: coroutine2-test, Configuration: Debug Win32 ------
1> Source.cpp
1>c:\users\lynden\boost_1_60_0\boost\context\execution_context.ipp(209): warning C4251: 'boost::context::execution_context::ptr_': class 'boost::intrusive_ptr<boost::context::detail::activation_record>' needs to have dll-interface to be used by clients of class 'boost::context::execution_context'
1>Source.obj : error LNK2001: unresolved external symbol "public: static class boost::intrusive_ptr<struct boost::context::detail::activation_record> boost::context::detail::activation_record::current_rec" (?current_rec#activation_record#detail#context#boost##2V?$intrusive_ptr#Uactivation_record#detail#context#boost###4#A)
1>D:\random projects\coroutine2-test\Debug\coroutine2-test.exe : fatal error LNK1120: 1 unresolved externals
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========
I have of course set the include directory to my boost directory and my linker additional directory to the boost/stage/lib directory.
You need to link against boost.context (used by boost.coroutine2).
Tell the compiler/linker where it can find the shared library of boost.context too.
You need to compile Boost using standard C++14 (option "-std=c++14"), otherwise Boost.Context will not provide the necessary implementation to support Boost.Coroutine2 and the compiler will fail to link.

Dependencies and errors when using atoi

I was given the task to refactor a very old project, and in these current days i'm checking the dependencies of the executables because for some reasons, they changed since 2009, passing from 4 to 14. To be more specific, my job is to keep the dependencies as they were before 2009, but with the changes to the code occuring until today.
I tracked down the instruction that was causing the trouble. It'a function inside a library used by the project:
chain(str, pps)
char *pps;
char *str;
{
int pp = 0;
pp = atoi(pps);
// ic sunt leones.
If i comment or replace atoi with an assignment of an integer like 0, 1 or 3, the library compile fine, but the executable that is using this .lib gives me these errors:
nafxcw.lib(wincore.obj) : error LNK2001: unresolved external symbol __imp__InitCommonControls#0
nafxcw.lib(wincore.obj) : error LNK2001: unresolved external symbol __imp__DragAcceptFiles#8
nafxcw.lib(appcore.obj) : error LNK2001: unresolved external symbol _ClosePrinter#4
nafxcw.lib(appcore.obj) : error LNK2001: unresolved external symbol _DocumentPropertiesA#24
nafxcw.lib(appcore.obj) : error LNK2001: unresolved external symbol _OpenPrinterA#12
nafxcw.lib(filecore.obj) : error LNK2001: unresolved external symbol __imp__SHGetFileInfoA#20
nafxcw.lib(filecore.obj) : error LNK2001: unresolved external symbol _GetFileTitleA#12
If otherwise i use a different value for the assignment, like 2, 4 or every other integer, everything compile correctly and work.
Any advice? What's happening here? Why this strange behaviour?
EDIT: apparently the problem is not the atoi. If i use an home made function that do anything and accept a char* and return an int or replacing directly the second parameter of the function chain with an int and assigning it directly i still receive the same errors.
You can try this :
include ('limits.h');
int my_getnbr(char *str)
{
int i;
long nbr;
int neg;
neg = 0;
nbr = 0;
i = 0;
if (str[0] == '-')
{
neg = 1;
str++;
}
while (str[i] >= '0' && str[i] <= '9')
{
nbr = nbr * 10 + (str[i++] - '0');
if (nbr > INT_MAX)
return (0);
}
return (neg ? (int)nbr * -1 : (int)nbr);
}
It's just a home made atoi like.
Edit : INT_MAX by Alter Mann.
Edit bis : if (nbr > INT_MAX) by Alter Mann again :)
the only thing I can think of is that the simplified function is being compiled out of existence, and the linker is then helpfully assuming that there is no code to link with in the library, and so it is being dropped, unfortunately it being the only thing that is forcing includes of those MFC libraries.
I have no idea why its even requiring stuff like OpenPinter - which is included in winspool.h (via windows.h) except to say that it sounds like you have a nasty MFC-based mess to sort out. It was never much good WRT tidy builds due to its dependence on specific includes specified in specific order.

Calling MATLAB from C++ errors: unresolved external symbol

I encounter several errors when calling my MATLAB function from C++. The main idea is: firstly compile a MATLAB function and generate DLL file, and then include .h and .lib files in C++. Finally, write .cpp to test and call the function. Here's my detailed steps and please tell me where I'm wrong.
(Using MATLAB 2012b and Visual C++ 2008, Windows 7 64-bit)
In MATLAB:
mbuild -setup and mex -setup to set Visual Microsoft Visual C++ 2008 SP1 as the compiler.
Create MyAdd.m in folder C:\Users\WangYudong\Documents\MATLAB\MyAdd_M and the function is like:
function [c] = MyAdd(a, b)
c = a + b;
mcc -W cpplib:libMyAdd -T link:lib MyAdd to compile MyAdd.m and generate several files including libMyAdd.dll, libMyAdd.h, libMyAdd.lib and other files.
In C++
Select VC++ Directories → Include files to add E:\MATLAB\R2012b\extern\include.
Select VC++ Directories → Library files to add
E:\MATLAB\R2012b\extern\lib\win64\microsoft and
C:\Users\WangYudong\Documents\MATLAB\MyAdd_M.
Select Linker → Input → Additional Dependencies to add new entries:
mclmcr.lib
mclmcrrt.lib
libmx.lib
libmat.lib
libMyAdd.lib
Create a new MyAdd_test.cpp and put libMyAdd.dll, libMyAdd.h and libMyAdd.lib in the same folder. Add libMyAdd.h in Header Files, libMyAdd.h and libMyAdd.lib in Resource Files.
Code of MyAdd_test.cpp is like:
#include "mclmcr.h"
#include "matrix.h"
#include "mclcppclass.h"
#include "libMyAdd.h"
int main() {
double a = 6;
double b = 9;
double c;
// initialize lib
if( !libMyAddInitialize()) {
std::cout << "Could not initialize libMyAdd!" << std::endl;
return -1;
}
// allocate space
mwArray mwA(1, 1, mxDOUBLE_CLASS);
mwArray mwB(1, 1, mxDOUBLE_CLASS);
mwArray mwC(1, 1, mxDOUBLE_CLASS);
// set data
mwA.SetData(&a, 1);
mwB.SetData(&b, 1);
// use function: MyAdd
MyAdd(1, mwC, mwA, mwB);
// get data
c = mwC.Get(1, 1);
printf("c is %f\n", c);
// terminate the lib
libMyAddTerminate();
// terminate MCR
mclTerminateApplication();
return 0;
}
At last, the result is
Compiling...
MyAdd_test.cpp
Linking...
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclTerminateApplication_proxy referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol _libMyAddTerminate referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol "__declspec(dllimport) void __cdecl MyAdd(int,class mwArray &,class mwArray const &,class mwArray const &)" (__imp_?MyAdd##YAXHAAVmwArray##ABV1#1#Z) referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol _libMyAddInitialize referenced in function _main
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclGetMatrix referenced in function "public: __thiscall mwArray::mwArray(unsigned int,unsigned int,enum mxClassID,enum mxComplexity)" (??0mwArray##QAE#IIW4mxClassID##W4mxComplexity###Z)
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclcppGetLastError referenced in function "public: static void __cdecl mwException::raise_error(void)" (?raise_error#mwException##SAXXZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _mclcppCreateError referenced in function "public: __thiscall mwException::mwException(void)" (??0mwException##QAE#XZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _ref_count_obj_addref referenced in function "public: __thiscall mwException::mwException(class mwException const &)" (??0mwException##QAE#ABV0##Z)
MyAdd_test.obj : error LNK2019: unresolved external symbol _ref_count_obj_release referenced in function "public: virtual __thiscall mwException::~mwException(void)" (??1mwException##UAE#XZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _error_info_get_message referenced in function "public: virtual char const * __thiscall mwException::what(void)const " (?what#mwException##UBEPBDXZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _array_ref_getV_int referenced in function "public: class mwArray __cdecl mwArray::GetPromoted(unsigned int,...)" (?GetPromoted#mwArray##QAA?AV1#IZZ)
MyAdd_test.obj : error LNK2019: unresolved external symbol _array_ref_set_numeric_mxDouble referenced in function "public: void __thiscall mwArray::SetData(double *,unsigned int)" (?SetData#mwArray##QAEXPANI#Z)
MyAdd_test.obj : error LNK2019: unresolved external symbol _array_ref_get_numeric_mxDouble referenced in function "public: __thiscall mwArray::operator double(void)const " (??BmwArray##QBENXZ)
C:\Users\WangYudong\Documents\Visual Studio 2008\Projects\MyAdd_C\Debug\MyAdd_C.exe : fatal error LNK1120: 13 unresolved externals
Actually, the work above is my test to call a custom MATLAB function from C++. My following work is to convert a MATLAB program to C++, which contains image processing functions like imread, edge, strel, etc. I've tried MATLAB Coder, but it can't convert MATLAB functions. So I try the method above. Is it an efficient way to convert those functions or should I implement them using OpenCV?
Before you start, make sure you have a supported compiler installed. That would be Visual C++ and possibly Windows SDK if you are using VS Express edition on a 64-bit Windows. Next you need to configure MATLAB by running these steps at least once:
>> mex -setup
>> mbuild -setup
Now given the following simple function:
MyAdd.m
function c = MyAdd(a,b)
c = a + b;
end
We want to build a C++ shared library using the MATLAB Compiler mcc:
>> mcc -N -W cpplib:libMyAdd -T link:lib MyAdd.m -v
This will produce a couple of files including a header file, a DLL, and an import library:
libMyAdd.h
libMyAdd.dll
libMyAdd.lib
Next we create a C++ program to test the above library:
MyAdd_test.cpp
#include "libMyAdd.h"
int main()
{
// initialize MCR and lib
if (!mclInitializeApplication(NULL,0)) {
std::cerr << "could not initialize the application" << std::endl;
return -1;
}
if(!libMyAddInitialize()) {
std::cerr << "Could not initialize the library" << std::endl;
return -1;
}
try {
// create input
double a[] = {1.0, 2.0, 3.0, 4.0};
double b[] = {5.0, 6.0, 7.0, 8.0};
mwArray in1(2, 2, mxDOUBLE_CLASS, mxREAL);
mwArray in2(2, 2, mxDOUBLE_CLASS, mxREAL);
in1.SetData(a, 4);
in2.SetData(b, 4);
// call function
mwArray out;
MyAdd(1, out, in1, in2);
// show result
std::cout << "in1 + in2 = " << std::endl;
std::cout << out << std::endl;
double c[4];
out.GetData(c, 4);
for(int i=0; i<4; i++) {
std::cout << c[i] << " " << std::endl;
}
} catch (const mwException& e) {
std::cerr << e.what() << std::endl;
return -2;
} catch (...) {
std::cerr << "Unexpected error thrown" << std::endl;
return -3;
}
// cleanup
libMyAddTerminate();
mclTerminateApplication();
return 0;
}
We could compile this program right from inside MATLAB using:
>> mbuild MyAdd_test.cpp libMyAdd.lib -v
>> !MyAdd_test
We could also compile it ourselves using Visual Studio. We start by creating a native console application, then set the project settings as follows:
From the menu, select "Project > Properties" and apply the settings to "All configurations" (both debug and release targets)
Under C/C++ properties, set the "Additional Include Directories" by adding both the directory containing the generated header file libMyAdd.h, in addition to the directory containing MATLAB's header files:
$matlabroot\extern\include
Similarly under "Linker", set the "Additional Library Directories". That would be the same directory as before containing libMyAdd.lib, as well as in my case:
$matlabroot\extern\lib\win32\microsoft
Then go to "Linker > Input" and add the following inside "Additional Dependencies":
libMyAdd.lib
mclmcrrt.lib
Finally under "Debugging > Environment", you might want to extend the PATH environment variable to include the directory containing the generated libMyAdd.dll file. That way you can directly hit F5 to compile run the program directly from inside VS. This will be something like:
PATH=%PATH%;C:\path\to\output\folder
If you do this kind of thing often, you could create a property sheet once, which could then be reused in other VC++ projects. See this answer for an example.