简体   繁体   中英

enum type and its linkage in C

why and how does the following code work?

both a and b have external linkage, but can they be declared by types of no linkage?

if not, why isn't there conflict between MyEnum_t in ac and MyEnum_t in bc?

ah

#ifndef _A_H_
#define _A_H_
void print_a_enum();
#endif

bh

#ifndef _B_H_
#define _B_H_
void print_b_enum();
#endif

ac

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

enum MyEnum{ ONE = 1, TWO = 2};
typedef enum MyEnum MyEnum_t;

MyEnum_t a = ONE;

void print_a_enum()
{
    printf("%d\n", a);
}

bc

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

enum MyEnum{ ONE = 3, TWO = 4};
typedef enum MyEnum MyEnum_t;

MyEnum_t b = ONE;

void print_b_enum()
{
    printf("%d\n", b);
}

main.c

#include "a.h"
#include "b.h"

int main()
{
     print_a_enum();
     print_b_enum()
}

print out: 1 3

gcc version 4.5.0 20100604 [gcc-4_5-branch revision 160292] (SUSE Linux)

The enum type and its values simply don't exist anymore after compilation. enum is a C construct, not anything to do with how your machine actually operates. You're perfectly allowed to give a particular enumeration type different values in different translation units. There's nothing the linker is going to be able to do about it later.

If you want to ensure that your enum type is consistent, you should probably put a single definition of it in a common header included by all translation units.

Editorial note: Don't use identifiers with leading underscores. They're reserved by the implementation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM