簡體   English   中英

在c99標准中`extern`關鍵字是可選的嗎?

[英]Is `extern` keyword is optional in c99 standards?

第一個文件是

/* OTHER.C */
#include <stdio.h>
#include <stdlib.h>

int i=35;
int fun1()
{
    i++;
    printf("%d\n",i);
    return 0;
}
int fun2()
{
    i--;
    printf("%d\n",i);
    return 0;
}

第二個文件是

/* MAIN.C */

#include <stdio.h>
#include "other.c"

int main()
{
    printf("%d\n",i);//WORKING FINE EVEN WITHOUT THE USE OF extern int i;

    fun1();//working fine

    fun2();//working fine

    getch();
    return 0;
}

之后#include "other.c"main.c ,可變i沿着fun1()fun2()即使沒有在聲明它做工精細main.c作為extern int iextern int fun1()extern int fun2()

但是在turbo c類的舊編譯器中,它顯示錯誤undeclared variable i

那么這是C99標准添加的一項附加功能嗎?

#include預處理程序指令的作用是將文件實際包含在#include

編譯器可以正確處理所謂的翻譯單元 ,即所有包含和宏替換之后預處理器的輸出。

所有這些意味着編譯器不會看到其他文件,只會看到一個大文件,在您的情況下,該文件包含來自other.c的代碼。

處理此類事情的通常方法是制作一個頭文件,例如主文件將包含的頭文件other.h ,然后包含函數原型(聲明)。 然后,讓構建系統生成兩個目標文件,每個源文件一個,並將目標文件鏈接在一起成為一個可執行文件。

如果您使用的是gcc則可以像下面這樣輕松完成:

$ gcc main.c other.c -o myprogram

這告訴編譯器將文件main.cother.c編譯為臨時目標文件,然后將它們鏈接在一起以創建myprogram可執行文件。

為此,您可能需要制作一個頭文件來聲明所需的內容:

/* OTHER.H */
#ifndef OTHER_H
#define OTHER_H

extern int i;
int fun1();
int fun2();

#endif

main.c文件中, #include頭文件而不是源文件。

暫無
暫無

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

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