簡體   English   中英

C++:localtime_s 在 GCC 中的位置

[英]C++: location of localtime_s in GCC

遵循文檔並像這樣使用gcc-11.2.0編譯

g++ -std=c++17 -pthread -O3 -flto -fPIC ...

我無法在我的程序中使用localtime_s

#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>

using SystemClock = std::chrono::system_clock;
const auto in_time_t = SystemClock::to_time_t(SystemClock::now());

struct tm buf; localtime_s(&in_time_t, &buf);
// error: there are no arguments to ‘localtime_s’ that depend on a template parameter, 
//        so a declaration of ‘localtime_s’ must be available [-fpermissive]

struct tm buf; std::localtime_s(&in_time_t, &buf);
// error: ‘localtime_s’ is not a member of ‘std’; did you mean ‘localtime’?

我做錯了什么或localtime_s在 GCC 中不可用? 還是僅適用於純 C 程序(例如,使用gcc -std=c11編譯)?

非常感謝您的幫助!

正如其他地方所指出的, _s函數最初是由 Microsoft 開發的。 它們作為規范性但可選的附錄 K 並入 C11。

不幸的是,標准指定的內容與 Microsoft 實施的內容之間存在差異。

微軟通過接口實現了localtime_s()

errno_t localtime_s(
   struct tm* const tmDest,
   time_t const* const sourceTime
);

標准 C11 需要localtime_s()

#define __STDC_WANT_LIB_EXT1__ 1
#include <time.h>
struct tm *localtime_s(const time_t * restrict timer,
       struct tm * restrict result);

POSIX 定義了localtime_r()

struct tm *localtime_r(const time_t *restrict timer,
       struct tm *restrict result);

如您所見,標准 C 和 Microsoft 函數localtime_r()具有非常不同的接口——參數順序相反,返回類型不同。 相比之下,標准 C 和 POSIX 函數之間的區別只是名稱。

這是_s函數的一個相當普遍的問題。 ISO 標准化的接口與 Microsoft 標准化的接口不同,這通常是有充分理由的。 您可以在問答中找到有關_s函數問題的其他信息您使用 TR 24731 '安全' 函數嗎? . 它有許多參考標准 C 和 Microsoft 變體_s (安全)函數之間差異的其他示例,以及一個討論文檔,該文檔表明安全函數並不是那么有用。

標准中指定的許多以_s結尾的函數最初是由 Microsoft 開發的,作為以_r結尾的函數的替代。

在 Linux 系統上, localtime_s未定義,但localtime_r已定義,並且具有相同的參數/返回類型,因此請改用它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM