红联Linux门户
Linux帮助

linux下使用gcc/g++编译代码时gets函数有错误

发布时间:2016-03-20 10:20:23来源:linux网站作者:SupperMary

今天在linux中使用个g++编译一个名为myfirst.cpp的代码的时候,出现如下错误:

myfirst.cpp: In function ‘int main()’:
myfirst.cpp:11:2: warning: ‘char* gets(char*)’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(cc);
^
myfirst.cpp:11:9: warning: ‘char* gets(char*)’ is deprecated (declared at /usr/include/stdio.h:638) [-Wdeprecated-declarations]
gets(cc);
^
/tmp/ccoHyVHf.o: In function `main':
myfirst.cpp:(.text+0xad): warning: the `gets' function is dangerous and should not be used.
/tmp/ccoHyVHf.o: In function `__static_initialization_and_destruction_0(int, int)':
myfirst.cpp:(.text+0x103): undefined reference to `std::ios_base::Init::Init()'
myfirst.cpp:(.text+0x112): undefined reference to `std::ios_base::Init::~Init()'
collect2: error: ld returned 1 exit status


仔细看错误信息得知,gets函数是危险的,具体信息请百度或者google,但是我用gets函数目的仅仅是为了输入一串字符,系统的用不了,我就自己写一个


ps:以下操作都实在linux的终端中进行,系统版本为ubuntu 14.04 LTS


打开终端(ctrl+Alt+T)

touch cstdio//创建文件cstdio,我使用的是C++

vim cstdio//编辑cstdio,并添加以下内容

#include<cstdio>
void mygets(char *str)
{
int i=0;
scanf("%c",&str[i]);
while(str[i++]!='\n')
{
scanf("%c",&str[i]);
}
str[i-1]=0;//  \0是字符数组中默认的字符串结尾,\0所对应的ascii码为0
}


这样自己的库函数就写好了,我不知道标准的库函数具体什么样,但是肯定不是我这样,嘿嘿

使用的时候,在头文件位置加上

#include"cstdio"  //是双引号,而不是尖括号

mygets(str);  //str书字符数组名

就可以在linux下间接使用gets函数了


若是使用C语言的写法的话,将

cstdio 文件的文件名

改为:

stdio.h,将该文件的里面的

#include<cstdio>

改为:

#include<stdio.h>


本文永久更新地址:http://www.linuxdiyf.com/linux/19080.html