Linux下" multiple definition of..."以及“第一次在此定义”的解决

在vs里使用了<sstream>库里的to_string函数,在改变编译环境到了gcc编译器下时,出现了一贯的重复声明问题,这种情况往往是未能考虑到不同编译环境下的函数存在性,往往需要我们通过条件编译进行解决。


譬如下面的int->string函数(注意包含头文件“#include<sstream>"

string to_string(int a)
{
    ostringstream ostr;
    ostr << a;
    string astr = ostr.str();

    return astr;
}

该函数如果未经条件编译在gcc下编译时出现了”错误:‘to_string’在此作用域中尚未声明“这样的错误说明,解决方案是:

#if defined(_MSC_VER)

#include <stdio.h>
#include<Windows.h>

#elif defined(__linux) || defined(__linux__)
#include <unistd.h>	
#include <sys/time.h>
#include<sstream>
#include <pthread.h>
#define  CRITICAL_SECTION   pthread_mutex_t
#define  _vsnprintf         vsnprintf
string to_string(int a)
{
	ostringstream ostr;
	ostr << a;
	string astr = ostr.str();

	return astr;
}

#endif

需要注意的是,如果main函数包含了其他文件,则经过相应条件编译依然无效,需要将条件编译放至包含main函数的文件之前,即可解决相应的问题。


(感谢阅览,若本文仍有疏漏,欢迎指正)

 
 

猜你喜欢

转载自blog.csdn.net/Osiris_sir/article/details/80735604