g++ 上的 strdup 错误与 c++0x
我有一些 C++0x 代码。我能够在下面重现它。下面的代码在没有 -std=c++0x
的情况下工作正常,但是我需要它来用于我的真实代码。
如何在 C++0x 中包含 strdup?使用 gcc 4.5.2
注意我正在使用 mingw。我尝试包括 cstdlib、cstring、string.h 并尝试使用 std::。运气不好。
>g++ -std=c++0x a.cpp
a.cpp: In function 'int main()':
a.cpp:4:11: error: 'strdup' was not declared in this scope
代码:
#include <string.h>
int main()
{
strdup("");
return 0;
}
I have some C++0x code. I was able to reproduce it below. The code below works fine without -std=c++0x
however i need it for my real code.
How do i include strdup in C++0x? with gcc 4.5.2
note i am using mingw. i tried including cstdlib, cstring, string.h and tried using std::. No luck.
>g++ -std=c++0x a.cpp
a.cpp: In function 'int main()':
a.cpp:4:11: error: 'strdup' was not declared in this scope
code:
#include <string.h>
int main()
{
strdup("");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

发布评论
评论(5)
strdup
可能不包含在您链接的库中(您提到了 mingw)。我不确定它是否在 c++0x 中;我知道它不在早期版本的 C/C++ 标准中。
这是一个非常简单的函数,您可以将其包含在您的程序中(尽管简单地将其称为“strdup”是不合法的,因为所有以“str”和小写字母开头的名称都保留用于实现扩展。)
char *my_strdup(const char *str) {
size_t len = strlen(str);
char *x = (char *)malloc(len+1); /* 1 for the null terminator */
if(!x) return NULL; /* malloc could not allocate memory */
memcpy(x,str,len+1); /* copy the string into the new buffer */
return x;
}
如果使用 C++,请考虑使用 C++ 标头。 string.h
是一个 C 标头,
是其 C++ 等效项。
#include <cstdlib>
#include <cstring>
#include <cstdio>
int main()
{
const char * first = "asdf qwerty";
printf("%s\n", first);
char * second = strdup(first);
second[4] = '\0';
printf("%s\n", second);
free(second);
return 0;
}
上面的代码可以在 GCC 9.4.0 g++ -Wall -Wextra -std=c++11
上正常编译。
额外的梗:如果你确实想要 C 语言中的 strdup()
(C23 之前),请使用 GCC 功能测试宏,例如 __STDC_WANT_LIB_EXT2__
或 _POSIX_C_SOURCE
。前者支持 C 标准扩展,后者支持 POSIX 扩展。在任何包含之前定义此宏非常重要,如下所示。
... 仅当实现定义了
__STDC_ALLOC_LIB__
并且用户将__STDC_WANT_LIB_EXT2__
定义为整数常量1
时,才保证 strdup 可用code> 在包含 string.h 之前。
#define __STDC_WANT_LIB_EXT2__ 1
/* ...or...
* #define _POSIX_C_SOURCE 200809L
*/
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
int main(void)
{
const char * first = "asdf qwerty";
printf("%s\n", first);
char * second = strdup(first);
second[4] = '\0';
printf("%s\n", second);
free(second);
return 0;
}
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
-std=gnu++0x (而不是 -std=c++0x)对我有用; -D_GNU_SOURCE 不起作用(我尝试使用交叉编译器,但也许它适用于其他类型的 g++)。
看来默认值(没有 -std=... 已通过)是“GNU C++”而不是“严格标准 C++”,因此“除了升级到 C++11 之外不要更改任何内容”的标志是 -std =gnu++0x,而不是-std=c++0x;后者意味着“升级到 C++11 并比默认情况更严格”。
-std=gnu++0x (instead of -std=c++0x) does the trick for me; -D_GNU_SOURCE didn't work (I tried with a cross-compiler, but perhaps it works with other kinds of g++).
It appears that the default (no -std=... passed) is "GNU C++" and not "strict standard C++", so the flag for "don't change anything except for upgrading to C++11" is -std=gnu++0x, not -std=c++0x; the latter means "upgrade to C++11 and be stricter than by default".