iostream linker error

怎甘沉沦 提交于 2019-12-12 08:23:07

问题


I have some old C code that I would like to combine with some C++ code.

The C code used to have has the following includes:

#include <windows.h>
#include <stdio.h>
#include <string.h>
#include "mysql.h"

Now I'm trying to make it use C++ with iostream like this:

#include <windows.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include "mysql.h"

But I keep getting the following linker errors when I compile:

[Linker error] undefined reference to `std::string::size() const'

[Linker error] undefined reference to `std::string::operator[](unsigned int) const'

[Linker error] undefined reference to `std::string::operator[](unsigned int) const'

[Linker error] undefined reference to `std::string::operator[](unsigned int) const'

[Linker error] undefined reference to `std::ios_base::Init::Init()'

[Linker error] undefined reference to `std::ios_base::Init::~Init()'

ld returned 1 exit status

How do I resolve this?

Edit: My compiler is Dev-C++ 4.9.9.2


回答1:


The C string.h header and the C++ string header are not interchangeable.

Overall, though, your problem is that the file is getting properly compiled, but the wrong runtime library is getting linked in.

Dev-C++ uses GCC. GCC can correctly determine the language in a file based on file extension, but won't link the right runtime library in unless you specifically ask it to (-lstdc++ at the command line). Calling GCC as "g++" (or, in your case, "mingwin32-g++") will also get the right language and will link the needed library.




回答2:


You need to link against your C++ runtime. It depends on your platform and compiler, but adding -lC to your linkline might do it.

So might linking using your C++ compiler rather than ld.

In any case, you probably have to link using the C++ compiler rather than ld if you want your C++ code to work correctly -- it's often required for exceptions and static initializers to work correctly...




回答3:


I got the same exact error when i was trying to compile with Cygwin (g++).

just add -L/usr/local/bin -L/usr/lib in the compilation rules and it should work.

This may be specific to Cygwin but it might help solve your problem too.



来源:https://stackoverflow.com/questions/264057/iostream-linker-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!