簡體   English   中英

在clang中強制使用C99兼容編譯

[英]Force C99 Compliant Compilation in clang

我正在嘗試編寫一些需要在c99模式下在solaris編譯的 C99代碼,但我無法訪問solaris機器。 相反,我正在嘗試使用clang在OSX上執行此操作。 但是,使用(文件min.c):

#include <stdio.h>
#include <string.h>

int main() {
  printf("%d\n", (int) strnlen("hello world", 5));
  return 0;
}

關於strnlen我沒有任何錯誤或警告

$ clang -std=c99 -pedantic-errors -Wall -Wextra min.c
$ ./a.out
5

即使strnlen是2008 posix擴展

這與:

Apple LLVM version 8.1.0 (clang-802.0.42)
Target: x86_64-apple-darwin16.7.0
Thread model: posix
InstalledDir: /Applications/Xcode.app/Contents/Developer/Toolchains/XcodeDefault.xctoolchain/usr/bin

是否有任何方法可以讓clang嚴格遵守c99,以便我有更好的機會來攜帶solaris?

可能有不一致的實現,很可能是由於頭問題,或者編譯器和頭之間不匹配。

在我的系統(Ubuntu 17.04,x86_64,clang 4.0.0)上,我得到:

$ clang -std=c99 -pedantic-errors -Wall -Wextra min.c
min.c:5:24: warning: implicit declaration of function 'strnlen' is invalid in C99 [-Wimplicit-function-declaration]
  printf("%d\n", (int) strnlen("hello world", 5));
                       ^
1 warning generated.
$ 

strnlen雖然沒有被C標准定義,但卻是一個保留的標識符。 當包含<string.h>時,保留以strwcsmem后跟小寫字母開頭的所有標識符。

C99 7.1.3p2說:

如果程序在保留它的上下文中聲明或定義標識符(除了7.1.4允許的標識符),或者將保留標識符定義為宏名稱,則行為是未定義的。

更新:正如MM的評論正確指出的那樣,你的程序沒有聲明或定義strnlen ; 它只是指它。 我將不得不考慮其影響。

由於您的程序具有未定義的行為(可能),因此不需要符合要求的實現來診斷它。 對於你的編譯器來說,警告你這一點肯定會更加用戶友好,但是如果不這樣做,就不會使它不符合要求。

如果您使用的是未保留的標識符,則需要編譯器對其進行診斷。 例如, stpcpy函數也是POSIX擴展名,但其名稱不是保留的。 如果此程序使用-std=c99 -pedantic-errors編譯時沒有警告或-std=c99 -pedantic-errors

#include <stdio.h>
#include <string.h>
int main(void) {
    char s[10];
    stpcpy(s, "hello");
    puts(s);
}

那么你有理由抱怨。

根據@ DietrichEpp的回答 ,以下似乎有效:

clang -std=c99 -Wpedantic -Wall -Wextra -D_POSIX_C_SOURCE=200112L min.c
min.c:5:24: warning: implicit declaration of function 'strnlen' is invalid in C99
      [-Wimplicit-function-declaration]
  printf("%d\n", (int) strnlen("hello world", 5));
                       ^
  1 warning generated.

標准手冊頁似乎支持這一點

POSIX.1-2001與C99一致,因此C99中標准化的所有庫函數也在POSIX.1-2001中標准化。

這使得XX和clang在OSX 10.12.6上產生了預期的結果。

暫無
暫無

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

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