【发布时间】:2012-07-11 13:13:42
【问题描述】:
我有点疑惑。我有我编译的项目
CFLAGS=-g -O2 -Wall -Wextra -Isrc/main -pthread -rdynamic -DNDEBUG $(OPTFLAGS) -D_FILE_OFFSET_BITS=64 -D_XOPEN_SOURCE=700
现在我想使用mkdtemp,因此包括unistd.h
char *path = mkdtemp(strdup("/tmp/test-XXXXXX"));
在 MacOSX 上,编译会给出一些警告
warning: implicit declaration of function ‘mkdtemp’
warning: initialization makes pointer from integer without a cast
但编译通过。虽然 mkdtemp 确实返回了一个非 NULL 路径,但访问它会导致 EXC_BAD_ACCESS。
问题一:模板为strdup()ed,结果非NULL。这到底怎么会导致 EXC_BAD_ACCESS?
现在在兔子洞的更深处。让我们摆脱警告。检查unistd.h我发现声明被预处理器隐藏了。
#if !defined(_POSIX_C_SOURCE) || defined(_DARWIN_C_SOURCE)
...
char *mkdtemp(char *);
...
#endif
将-D_DARWIN_C_SOURCE 添加到构建中可以消除所有问题,但给我留下了特定于平台的构建。 10.6 手册页只是说
Standard C Library (libc, -lc)
#include <unistd.h>
从构建中删除 _XOPEN_SOURCE 在 OSX 上是可行的,但在 Linux 下无法编译
warning: ‘struct FTW’ declared inside parameter list
warning: its scope is only this definition or declaration, which is probably not what you want
In function ‘tmp_remove’:
warning: implicit declaration of function ‘nftw’
error: ‘FTW_DEPTH’ undeclared (first use in this function)
error: (Each undeclared identifier is reported only once
error: for each function it appears in.)
error: ‘FTW_PHYS’ undeclared (first use in this function)
问题 2:那么您将如何解决这个问题?
我发现的唯一解决方法是 #undef _POSIX_C_SOURCE 在 unistd.h 包含之前...但这感觉就像一个丑陋的黑客。
【问题讨论】:
-
mkdtemp 不是基本 POSIX ——根据pubs.opengroup.org/onlinepubs/9699919799/functions/mkstemp.html,它位于扩展 API 中。段错误:你确定你
-
你传入的是 char * 而不是 const char *?
-
我知道
mkdtemp不是基础 POSIX。但似乎_XOPEN_SOURCE导致_POSIX_C_SOURCE被定义。仍然想使用mkdtemp和ftwAPI。 -
至于
const char*见上文。这是通过strdup复制的文字。所以应该没问题。 -
@H2CO3 er,CX 那里实际上意味着它在 POSIX 中,但不在 ANSI C 中。问题是 OSX 显然不支持它添加的 POSIX 版本。