0
votes

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 a.c and MyEnum_t in b.c?

a.h

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

b.h

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

a.c

#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);
}

b.c

#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)

1
Side node: you can simple write typedef enum{ ONE = 1, TWO } MyEnum; in single stepGrijesh Chauhan

1 Answers

3
votes

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.