2017-07-21 9 views
3

愚かな質問ですが、おそらくヘッダーがありませんが、マニュアルページには#include <linux/random.h>が必要です。getrandom()がコンパイルされないのはなぜですか?

#include <stdio.h> 
#include <stdint.h> 
#include <stdlib.h> 
#include <linux/random.h> 

#define BITS 8192 
#define BYTES (BITS >> 3) 

int main() { 
    uint8_t array[BYTES]; 

    printf("started..."); 
    int r = getrandom(array, BYTES, 0); 
    if (r) exit(1); 

    return 0; 
} 

エラーは次のとおりです。

[email protected]:~/lunch/bitarray$ make && ./bitarray 
clang -g -Wall -Wpedantic -Werror -std=c11 -O2 -save-temps bitarray.c -o bitarray 
bitarray.c:13:10: error: implicit declaration of function 'getrandom' is invalid in C99 [-Werror,-Wimplicit-function-declaration] 
int r = getrandom(array, (8192 >> 3), 0); 
     ^
1 error generated. 
Makefile:10: recipe for target 'bitarray' failed 
make: *** [bitarray] Error 1 

は(。また、GCCに失敗した)

[email protected]:~/lunch/bitarray$ cat /etc/lsb-release 
DISTRIB_ID=Ubuntu 
DISTRIB_RELEASE=16.04 
DISTRIB_CODENAME=xenial 
DISTRIB_DESCRIPTION="Ubuntu 16.04.2 LTS" 
[email protected]:~/lunch/bitarray$ uname -a 
Linux purple 4.4.0-83-generiC#106-Ubuntu SMP Mon Jun 26 17:54:43 UTC 2017 x86_64 x86_64 x86_64 GNU/Linux 
+3

をうん、あなたのコンパイルエラーがその関数のプロトタイプは、ヘッダーにされていないと正確に一致しています。ドキュメンテーション、ええ? – Bathsheba

+0

@MichaelWalz 'chris @ purple:〜/ lunch/bitarray $ make && ./bitarray clang -g -Wall -Wpedantic -Werror -std = c11 -O2 -save-temps bitarray.c -oビット配列 bitarray.c: 5:10:致命的なエラー: 'sys/random.h'ファイルが見つかりません #include ' – fadedbee

+0

ここにマンページは' 'と言っています - それは間違っています:またはディレクトリ! –

答えて

4

これは、いくつかのLinuxシステムがgetrandomのmanページ、正しいシステムコールの定義を持っていることが表示されますが、 C関数はありません。それはあなた自身を作成するのに十分なあなたを与えるん:

// _GNU_SOURCE should be set before *any* includes. 
// Alternatively, pass to compiler with -D, or enable GNU extensions 
// with -std=gnu11 (or omit -std completely) 
#define _GNU_SOURCE 
#include <unistd.h> 
#include <sys/syscall.h> 

int my_getrandom(void *buf, size_t buflen, unsigned int flags) 
{ 
    return (int)syscall(SYS_getrandom, buf, buflen, flags); 
} 

// remove this when we have a real getrandom(): 
#define getrandom my_getrandom 
// and replace it with 
// #include <linux/random.h> 
#include <stdio.h> 
#include <stdint.h> 
#include <stdlib.h> 

#define BITS 8192 
#define BYTES (BITS >> 3) 

int main() { 
    uint8_t array[BYTES]; 

    printf("started...\n"); 
    int r = getrandom(array, sizeof array, 0); 
    return r; 
} 
+0

GNU拡張機能をデフォルトで有効にするには、 '-std = gnu11'を指定してコンパイルしてください。 '-std = c11'を使用すると、明示的に有効にされていない限り、拡張機能がオフになります。これは'#define'の機能です。 –

+0

ああ、私は習慣によって標準Cをコンパイルします。 –

+1

私はデフォルトで '-std = c11'を使います。私のコードはGNU以外の環境(macOSなど)で動作しなければならないので、私はしばしばGNUソースを使いません。 –

関連する問題