V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rookiemaster
V2EX  ›  C

在 c 语言中, int a;是 declaration 还是 definition

  •  
  •   rookiemaster · 36 天前 · 1815 次点击
    这是一个创建于 36 天前的主题,其中的信息可能已经有所发展或是发生改变。

    已知 extern int a;是 declaration

    13 条回复    2024-03-29 19:24:01 +08:00
    febhfrswsz
        1
    febhfrswsz  
       36 天前 via Android
    然后呢
    kk7896
        2
    kk7896  
       36 天前
    definition
    rookiemaster
        3
    rookiemaster  
    OP
       36 天前 via iPhone
    又看到了一个东西叫 Storage-class specifiers ,好复杂
    nyxsonsleep
        4
    nyxsonsleep  
       36 天前
    以下示例演示的声明也是定义:

    C++

    // Declare and define int variables i and j.
    int i;
    int j = 10;

    下面这些声明不是定义:

    C++

    extern int i;
    char *strchr( const char *Str, const char Target );

    https://learn.microsoft.com/zh-cn/cpp/cpp/declarations-and-definitions-cpp?view=msvc-170
    vituralfuture
        5
    vituralfuture  
       36 天前 via Android
    定义,因为分配了内存
    realJamespond
        6
    realJamespond  
       36 天前   ❤️ 1
    在头文件是声明,在源文件是定义
    FranzKafka95
        7
    FranzKafka95  
       35 天前 via Android
    赞同楼上的
    mintist
        8
    mintist  
       35 天前
    有内存空间分配就是定义,声明对应汇编的符号,仅仅为了告诉你有这个东西在这里
    koebehshian
        10
    koebehshian  
       35 天前   ❤️ 1
    The C Programming Language 附录 A ,A.8 Declarations 中说:

    ```
    Declarations specify the interpretation given to each identifier; they do not necessarily reserve storage associated with the identifier. Declarations that reserve storage are called definitions.
    ```

    所以,首先要明白,definition 是 declaration 的一种,区别在于 definition 为变量预留了内存
    所以,你的问题应该修改为:int a; 有没有预留内存。

    答案是:大多数情况下预留了内存。只有一种情况,就是写在函数外面

    A.10.2 External Declarations 中说:

    ```
    An external object declaration that does not have an initializer, and does not contain the extern specifier, is a tentative definition. If a definition for an object appears in a translation unit, any tentative definitions are treated merely as redundant declarations.
    ```

    意思是,int a; 写在函数外面,编译器先会将其待定;如果发现整个编译单元(一般是一个预处理过的源文件)中有多个这样的写法,则多余的就被当作没有预留内存的 declarations 了
    LGA1150
        11
    LGA1150  
       33 天前
    @realJamespond
    没有 extern 的话,即使在头文件里也是定义
    hkdcl
        12
    hkdcl  
       33 天前 via Android
    定义。函数外面的全局变量会初始化为 0 ,里面的会是该内存原来的值
    pagxir
        13
    pagxir  
       29 天前 via Android
    @realJamespond #6 事实上 c 语言编译器眼里并不存在头文件一说,你可以把.h 改名成.c , 并在另一个 c 文件里 include 它
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   957 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 19:37 · PVG 03:37 · LAX 12:37 · JFK 15:37
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.