簡體   English   中英

請任何人在編寫 c 程序時向我解釋這個警告(使用 extern 關鍵字)

[英]Please can anyone explain me this warning while writing a c program(use of extern keyword)

文件名:- next.c

extern int global_var = 2;

文件名:-try.c

#include <stdion.h>
#include "next.c"
void main()
{
printf("%d", global_var);
}

我得到的警告

In file include form try.c:2:0:
next.c.1.12: warning: 'globl_var' initialized and declared 'extern'
 extern in global_var = 22;
           ^~~~~~~~~

警告本身會告訴您您的代碼是錯誤的。 這些消息可以“翻譯”成類似這樣的內容:“將變量聲明為 extern同時分配一個值是錯誤的。

您似乎誤解了使用包含文件的正常方式。 你不這樣做:

#include "next.c"

你所做的是

#include "next.h"

那就是......一個c文件包含一個單元的源代碼。 相應的 h 文件包含有關您要與其他單元共享的單元的信息(也稱為 c 文件)。

嘗試這個:

下一個.h:

extern int global_var;  // Tell other c-files that include next.h
                        // that a int-variable with name global_var
                        // exists

下一個。c:

int global_var = 2;     // Define and initialize global_var

並在 try.c 中執行:

#include "next.h"       // Include next.h to know what the unit next.c
                        // makes available for use in try.c

以上是針對單元next.c定義的全局變量。 對於功能幾乎相同。

Assume that next.c implements a function foo that you want try.c to call... Then you do the same, ie you write the functions source code in next.c and use next.h to tell other units that the function is可用的。 喜歡:

下一個.h:

extern int global_var;  // Tell other c-files that include next.h
                        // that a int-variable with name global_var
                        // exists

void foo(int a, int b);  // Tell other c-files that include next.h
                         // that a function with name foo
                         // exists

下一個。c:

int global_var = 2;     // Define and initialize global_var

void foo(int a, int b)   // Define foo
{
    ... source code ...
}

並在 try.c 中使用它:

#include "next.h"       // Include next.h to know what the unit next.c
                        // makes available for use in try.c

#include "next.h"       // Include next.h to know what the unit next.c
                        // makes available for use in try.c

int bar()
{
    int x = 0;
    int y = 42;
    foo(x, y);    // Call function foo in unit next.c
    ....
}

extern用於告訴編譯器變量是從 scope 中聲明的。

一、c

#include <stdio.h>
#include "second.h"

int main(){

    extern const float pi;

    printf("pi : %f\n" , pi);

    return 0;
}

第二個.h

const float pi = 3.148;

output

圓周率:3.148000

為什么要使用外部?

防止本地重新聲明變量並使代碼更具可讀性和可理解性

示例錯誤
一、c

#include <stdio.h>
#include "second.h"

int main(){

    extern const float pi;
    const float pi;

    printf("pi : %f\n" , pi);

    return 0;
}

output

首先。c:在 function '主要':
first.c:7:17:錯誤:重新聲明沒有鏈接的“pi”
7 | 常量浮點數;
| ^~
在 first.c:2 中包含的文件中:
second.h:1:13:注意:'p 的先前定義
' 類型為 'float'
1 | 常量浮動 pi = 3.148;
| ^~

extern 告訴編譯器 extern 聲明的符號是在不同的源文件或翻譯單元中定義的。

當您為外部符號賦值時,您基本上會說“定義在其他地方,但定義是 [x]”

要解決這個問題,您應該在沒有“extern”的地方“定義”變量。

暫無
暫無

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

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