【问题标题】:Get the current working directory in C on windows在 Windows 上获取 C 中的当前工作目录
【发布时间】:2015-02-19 13:30:51
【问题描述】:

出于某种奇怪的原因,当我尝试将函数 get_current_dir_name 与 MinGW GCC 编译器一起使用时, 我在链接上得到了这个结果:

undefined reference to `get_current_dir_name'
collect2.exe: error: ld returned 1 exit status

但是,我只有在使用这样的功能时才会得到这个

printf("%i", get_current_dir_name());

或者这个

printf("%s", get_current_dir_name());

当我尝试做的时候

printf(get_current_dir_name());

我明白了,这是没有意义的,因为该函数返回一个 char *,根据文档:

tester.c: In function 'main':
tester.c:16:2: warning: passing argument 1 of 'printf' makes pointer from integer without a cast [enabled by default]
  printf(get_current_dir_name());
  ^
In file included from tester.c:1:0:
c:\mingw\include\stdio.h:294:37: note: expected 'const char *' but argument is of type 'int'
 _CRTIMP int __cdecl __MINGW_NOTHROW printf (const char*, ...);

Google 似乎真的不喜欢谈论 C,因为我可以找到如何在几乎所有现有语言上获取 workdir,除了 C。唯一弹出的是一些文档,它们描述了 3 个函数:getcwd、getwd 和获取当前目录名称。我真的很想使用 get_current_dir_name 之一,因为它很干净。

我该如何处理?这是一个 minGW 错误吗?还是我错过了什么?

【问题讨论】:

标签: c windows gcc mingw ld


【解决方案1】:

您显然没有包含任何包含get_current_dir_name() 声明的标头。因此,编译器将假定返回值为int,这不是printf() 的有效第一个参数(您应该提高警告级别,这样您会得到一个错误,而不仅仅是一个警告)。

此外,链接失败,因此您也不要链接到实现该函数的库,这是预期的:get_current_dir_name() 是 GNU 扩展,而不是 C 标准库的一部分。

在 Windows 上,您需要使用 Windows API 提供的等效功能,即GetCurrentDirectory(),在windows.h 中声明。

【讨论】:

    猜你喜欢
    • 2020-06-03
    • 1970-01-01
    • 2010-09-18
    • 2014-03-10
    • 2018-04-17
    • 1970-01-01
    • 2012-07-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多