Why does LNK2005 Error disappear? - c++

In visual studio 2012 I have a small console c++ project with the following code
Main.cpp:
#include "../TestLib/LibFunction.h"
int _tmain(int argc, _TCHAR* argv[])
{
int number = libFunction(7);
return 0;
}
and in a static library project LibTest I have
LibFunction.h:
#pragma once
int libFunction( int a );
LibFunction.cpp
int libFunction( int a )
{
return a + 1;
}
This compiles and runs fine. (The Library is added as a reference and linked in implicitly)
If I now add this code to main project
int libFunction( int a )
{
return 7 * a;
}
when I try to build the program I get this error
Main.obj : error LNK2005: "int __cdecl libFunction(int)" (?libFunction##YAHH#Z) already defined in TestLib.lib(LibFunction.obj)
which is fair enough. However if I now just try building again ( doing nothing else ) the link completes without error and the program runs fine with the new libFunction being used.
Why does the error go away?
Why is there this inconsistency? Either it is valid to override a function in a library or its not. I should not get an error and then without doing anything get no error.
I am trying to understand the behaviour for a much larger project where again there are duplicate symbols defined in the exe and referenced lib and sometimes I get errors and sometimes not.

Normally it should be OK to override library symbols. There are still caveats; for instance, if library code contains several external functions in the same source file, and you want to override one of them, you may have to override all the others. Otherwise you will get the multiple definitions error. But in this case you will get it consistently.
However such overrides may throw off the incremental linker, especially if it's the first build with the override. A full rebuild should be enough to correct the error until you add more overrides. If this is a problem, just disable incremental linking.

Related

VS 2022: "Unresolved external" error when calling methods that are defined outside of the class definition

So, I've tried to run the simplest C++ program imaginable in Visual Studio 2022:
main.cpp:
#include "TestClass.h"
int main() {
TestClass().testMethod();
}
TestClass.h:
#pragma once
class TestClass {
public:
void testMethod();
};
TestClass.cpp:
#include "TestClass.h"
inline void TestClass::testMethod() {
}
But for some reason, I get nothing but a linker error:
error LNK2019: unresolved external symbol "public: void __cdecl TestClass::testMethod(void)" (?testMethod#TestClass##QEAAXXZ) referenced in function main
I know that there are tons of questions on Stack Overflow discussing that specific error, but I wasn't able to find anything that applied to my situation, except for this one, which doesn't have an answer.
All files are included in the project (everything was generated in Visual Studio), I do not get any warnings from IntelliSense, and every file on its own compiles just fine (using Ctrl+F7)
I have no clue what is going on and would appreciate any help.
In C++ inline functions must have their body present in every translation unit from which they are called.
Removing inline doesn't change anything
Try to test it. I'm not the only one who proves that inline causes the lnk error. As
Sedenion says, it's a usage error.
I recommend reporting this wrong behavior to Developer Community and posting the link in this thread.

Including files from a seperate project in the same solution in Visual studio - LNK2001?

I had a solution named fun.sln with a project called fun.vcxproj.
I created a whole bunch of name spaces ready to be used.
I made another project called no_more_fun.vcxproj.
I added the includes directory for fun.vcxproj to the configuration of no_more_fun.vcxproj.
I added this to no_more_fun.cpp
#include "candy.h"
void main(void)
{
candy::get();
return;
}
candy.h is in the default directory for fun.vcxproj(which was added to the config)
But I get...
LNK2001 unresolved external symbol "int __cdecl candy::get(unsigned long)" (?get#candy##YAHK#Z) .....
Visual Studio shows no error before compiling.
The "candy" namespace works fine in the "fun" project so idn...
Is there a guide or something so that i can understand how i can go about sharing code efficiently among different projects within ONE solution?
This is a linker error. You didn't get any error at compile time, because the compiler found the candy::get() method in candy.h header, but the implementation (which I suppose is in a candy.cpp file) is not found by the linker.
Just add candy.cpp too to no_more_fun.vcxproj.
ps. I didn't observe but in the error message you can see that the function waits a parameter.
call it like this:
unsigned long foo = 0;
candy::get(foo);
This is going to sounds stupid but...i just dragged the files in to visual studio so that the no_more_fun project had the "files" in its "directory" too.
wow... I shouldn't need to do that...Am I wrong?(sarcasm).

xDispatch LNK2019 Linker error Unresolved Externals

I realise this i mighty popular question, but all of the other posts seem to follow the same idea. That the include, lib and bin folder need to be correctly configured. I believe my settings are correct, but i am still getting the LNK2019 error. What am i doing wrong?
Using Visual Studio 2012
I am getting the infamous LNK2019 error. Many posts of this issue seem to think it is a linker issue. I am using a library with lib and dll files. The project folder has an include, bin and lib folder that need to be configured in the project.
Install instructions are here.....
http://opensource.mlba-team.de/xdispatch/docs/current/tutorial.html
However, this is clearly a linker issue as it occurs in other libraries of a similar type. I have followed the instructions for other posts and i'm still a bit lost. I believe this should be correct, but i have tried virtually every possible combination. Don't get it.
My Project Configurations
C++ -> General -> Additional Include Directories.
C:\Users\Daniel\Documents\Visual Studio 2012\Projects\LibDispatchTest\xdispatch_0.7.2_Visual Studio 10_i386\include;%(AdditionalIncludeDirectories)
Linker -> General -> Additional Library Directories
C:\Users\Daniel\Documents\Visual Studio 2012\Projects\LibDispatchTest\xdispatch_0.7.2_Visual Studio 10_i386\lib;%(AdditionalLibraryDirectories)
Linker -> Input -> Additional Dependancies:
.....uuid.lib;odbc32.lib;odbccp32.lib;xdispatch.lib;%(AdditionalDependencies)
Environment Variables.
I have the PATH variable set.
C:\Chocolatey\bin;C:\Users\Daniel\Documents\Visual Studio 2012\Projects\VisionBase\xdispatch_0.7.2_Visual Studio 10_i386\bin;
The error messages are:
error LNK2019: unresolved external symbol "_declspec(dllimport) public: void __thiscall xdispatch::queue::async(class std::function<void __cdecl(void)> const &)" (__imp?async#queue#xdispatch##QAEXABV?$function#$$A6AXXZ#std###Z) referenced in function "void __cdecl some_function(void)" (?some_function##YAXXZ) c:\Users\Daniel\documents\visual studio 2012\Projects\LibDispatchTest\LibDispatchTest\main.obj LibDispatchTest
error LNK1120: 1 unresolved externals c:\users\daniel\documents\visual studio 2012\Projects\LibDispatchTest\Debug\LibDispatchTest.exe 1 1 LibDispatchTest
Seriously, am totally lost and i do not see what i am doing wrong here.
EDIT 1
This is similar to a sample from the above link, but modified to just couNT 1000000^2 and print some stuff. We just want to be able to compile and run this sample and i can correct my larger project exhibiting this issue. This project was made fresh with the simplest code that is representative of what i need to get working. Both this sample and my other project have this problem and produce the same error.
#include <xdispatch/dispatch>
#include <vector>
#include <cmath>
class SomeData {
public:
std::vector<double> a;
std::vector<double> b;
std::vector<double> c;
std::vector<double> results;
};
void do_calculations(SomeData* sd){
// our output will go in here
sd->results = std::vector<double>(sd->a.size());
// the calculation - running on one thread only
for(unsigned int i = 0; i < 1000000; i++){
sd->results[i] = 0;
for(unsigned int j = 0; j < 10000000; j++){
for(unsigned int z = 0; z < sd->c.size(); z++){
std::cout << i << " " << j << std::endl;
}
}
} }
/* This function is getting called from your main thread also powering the user interface */
void some_function() {
SomeData* sd = new SomeData();
xdispatch::global_queue().async(${
// execute the heavy code
do_calculations(sd);
}); }
int main() {
some_function();
return 0; }
Is anyone able to help?
The binaries you used where built with and for MS Visual Studio 2010. Since then the CRT has changed quite a bit and might not be compatible, especially when parts of the STL is used. Because of that I do not recommend to ever use a C++ dll built with VS 2010 for use in VS 2012 or later. It could be that building and linking succeeds but during runtime you experience weird and unexpected issues. In your case even linking won’t work because std::function has changed its signature in the meantime, so lucky enough you already discover those incompatibilities at compile time.
I assume xdispatch will work just fine with VS2012 and maybe even VS2013, however you will need to do your own build for that. All information needed is summarized at [1]. A tarball containing the sources can always be found at [2].
[1] http://opensource.mlba-team.de/xdispatch/docs/current/requirements.html
[2] http://opensource.mlba-team.de/xdispatch/files/

Creating static library and linking to it with premake

I am currently trying to learn how to use premake 4 in order to apply it to the OpenGL sdk. I am currently trying to make a Visual Studio 2010 solution that constructs 2 projects, one being a static library, the other contains a single main source file, with the main method.
This project is extremely simple, and is solely for the purpose of learning premake. In the static library project, named Test, I have 2 files, Test.h and Test.cpp. Test.h contains the prototype for the method print(). print() simply prints a line to the console. Using premake, I linked the static library to the Main project, and in main.cpp I have included the Test.h file. My problem is this: in VS2010 I get this error when I attempt to build:
1>main.obj : error LNK2019: unresolved external symbol "void __cdecl print(void)" (? print##YAXXZ) referenced in function _main
1>.\Main.exe : fatal error LNK1120: 1 unresolved externals
Here is my code in the 4 files, the premake4.lua:
solution "HelloWorld"
configurations {"Debug", "Release"}
project "Main"
kind "ConsoleApp"
language "C++"
files{
"main.cpp"
}
configuration "Debug"
defines { "DEBUG" }
flags { "Symbols" }
configuration "Release"
defines { "NDEBUG" }
flags { "Optimize" }
links {"Test"}
project "Test"
kind "StaticLib"
language "C++"
files{
"test.h",
"test.cpp"
}
Test.cpp:
#include <iostream>
void print(){
std::cout << "HELLO" << std::endl;
}
Test.h:
void print();
Main.cpp:
#include <conio.h>
#include "test.h"
int main(){
print();
getch();
return 0;
}
If you are wondering why there is a getch() there, on my computer the console immediately closes once it reaches return 0, so I use getch() to combat that issue, which forces the window to wait until the user has pressed another key. Any advice on this issue would be wonderful, because I simply am not sure what the problem is. If it is something simple please dont castrate me on it, I have very little experience with premake and static libraries, which is why I am trying to learn them.
links {"Test"}
Lua is not Python. Whitespace is irrelevant to Lua, just like whitespace doesn't matter to C++. So your links statement only applies to the "Release" configuration. If you want it to apply to the project as a whole, it needs to go before the configuration statement, just like your kind, files, and other commands.
Premake4 works this way so that you could have certain libraries that are only used in a "Release" build (or Debug or whatever). Indeed, you can put almost any project command under a configuration. So you can have specific files that are used only in a debug build, or whatever.

error LNK2019: unresolved external symbol _WinMain#16 referenced in function ___tmainCRTStartup

While I am running the simple code as below I have two errors as following:
#include <iostream>
#include <string>
using namespace::std;
template <class Type>
class Stack
{
public:
Stack (int max):stack(new Type[max]), top(-1), maxsize(max){}
~Stack (void) {delete []stack;}
void Push (Type &val);
void Pop (void) {if (top>=0) --top;}
Type& Top (void) {return stack[top];}
//friend ostream& operator<< (ostream&, Stack&);
private:
Type *stack;
int top;
const int maxSize;
};
template <class Type>
void Stack <Type>:: Push (Type &val)
{
if (top+1<maxsize)
stack [++top]=val;
}
Errors:
MSVCRTD.lib(crtexew.obj) : error LNK2019: unresolved external symbol _WinMain#16 referenced in function ___tmainCRTStartup
What Should I do?
Thats a linker problem.
Try to change Properties -> Linker -> System -> SubSystem (in Visual Studio).
from Windows (/SUBSYSTEM:WINDOWS) to Console (/SUBSYSTEM:CONSOLE)
This one helped me
As the others mentioned you can change the SubSystem to Console and the error will go away.
Or if you want to keep the Windows subsystem you can just hint at what your entry point is, because you haven't defined ___tmainCRTStartup. You can do this by adding the following to Properties -> Linker -> Command line:
/ENTRY:"mainCRTStartup"
This way you get rid of the console window.
If you are having this problem and are using Qt - you need to link qtmain.lib or qtmaind.lib
Besides changing it to Console (/SUBSYSTEM:CONSOLE) as others have said, you may need to change the entry point in Properties -> Linker -> Advanced -> Entry Point. Set it to mainCRTStartup.
It seems that Visual Studio might be searching for the WinMain function instead of main, if you don't specify otherwise.
Include <tchar.h> which has the line:
#define _tWinMain wWinMain
If you use Unicode Character Set, but the entry wasn't set, you can specify /ENTRY:"wWinMainCRTStartup"
If you actually want to use _tWinMain() instead of main()
make sure your project relevant configuration have
Linker-> System -> SubSystem => Windows(/SUBSYSTEM:WINDOWS)
C/C++ -> Preprocessor -> Preprocessor Definitions => Replace _CONSOLE with _WINDOWS
In the c/cpp file where _tWinMain() is defined, add:
#include <Windows.h>
#include <tchar.h>
i don't see the main function.
please make sure that it has main function.
example :
int main(int argc, TCHAR *argv[]){
}
hope that it works well. :)
If your project is Dll, then the case might be that linker wants to build a console program. Open the project properties. Select the General settings. Select configuration type Dynamic Library there(.dll).
I'm not sure where to post this answer of mine but I think it's the right place.
I came across this very error today and switching the subsystems didn't change a thing.
Changing the 64bit lib files to 32bit (x86) did the trick for me, I hope it will help someone out there !
Your tried to turn that source file into an executable, which obviously isn't possible, because the mandatory entry point, the main function, isn't defined. Add a file main.cpp and define a main function. If you're working on the commandline (which I doubt), you can add /c to only compile and not link. This will produce an object file only, which needs to be linked into either a static or shared lib or an application (in which case you'll need an oject file with main defined).
_WinMain is Microsoft's name for main when linking.
Also: you're not running the code yet, you are compiling (and linking) it. C++ is not an interpreted language.
If you are using CMake, you can also get this error when you set SET(GUI_TYPE WIN32) on a console application.
The erudite suggestions mentioned above will solve the problem in 99.99% of the cases. It was my luck that they did not. In my case it turned out I was including a header file from a different Windows project. Sure enough, at the very bottom of that file I found the directive:
#pragma comment(linker, "/subsystem:Windows")
Needless to say, removing this line solved my problem.