簡體   English   中英

C:初始化元素不是恆定的

[英]C : initializer element is not constant

我正在C學習fork() ,並且遇到了以下錯誤:

app.c:13:1: warning: data definition has no type or storage class [enabled by default]
app.c:13:1: error: initializer element is not constant
app.c:15:1: error: expected identifier or ‘(’ before ‘if’
app.c:20:1: error: expected identifier or ‘(’ before ‘else’
app.c:26:1: error: expected identifier or ‘(’ before ‘else’

這是源代碼:

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>

int f;
pid_t pid;

char msga[] = "abcd";
char msgb[] = "wxyz";

f = open("toto", O_WRONLY|O_TRUNC|O_CREAT,S_IRUSR|S_IWUSR);

if ((pid = fork()) == -1) {
    perror("fork");
    exit(EXIT_FAILURE);
}

else if (pid == 0) {
    wait(NULL);
    write(f, &msga, strlen(msga));
    close(f);
}

else {
    wait(NULL);
    write(f, &msgb, strlen(msgb));
    close(f);
}

您需要將所有內容(在#include行之后)包裝在一個函數中!

int main(void)
{
 ...
}

您可能需要添加一個return 0; 最后在那里。

在這里的快速測試中,我還需要添加:

#include <unistd.h>
#include <string.h>

要分別獲取fork(2)strlen(3)的聲明。

暫無
暫無

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

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