Greeneco
Greeneco

Reputation: 741

Define a enum data types for use in several files

I have several files like main.c, main.h, some_funcs.c and some_funcs.h.

main.h is included in main.c
main.h include some_funcs.h
some_funcs.c include some_funcs.h

When I now define a new data type like:

//Datatypes
enum _bool {
   false = 0,
   true = 1
};

typedef enum _bool Bool;

If i define it in e.g. main.h and want to use it in some_func.c it does not work. Is there a ways to define it somewhere without always include the header where it is defined?

Upvotes: 0

Views: 65

Answers (3)

chmike
chmike

Reputation: 22174

Put the definition in some_funcs.h. This will make it visible in main.h, main.c, some_funcs.h and some_funcs.c.

A more general solution is to put common data types into a file named common.h for instance.

You then include this file in all header files.

This would be the content of the common.h file. The ifdef is to ignore the content of the file if it was already included.

#ifndef COMMON_H
#define COMMON_H

//Datatypes
enum _bool {
   false = 0,
   true = 1
};

typedef enum _bool Bool;

#endif

Upvotes: 3

Vlad from Moscow
Vlad from Moscow

Reputation: 311048

Is there a ways to define it somewhere without always include the header where it is defined?

It sounds like can I use a definition of a type without defining it.:)

You should include the header file where the enumeration and typedef are defined in each module that uses it.

Take into account that there is 1) type _Bool in C and 2) standard header <stdbool.h> where macros bool, false, and true are already defined.

Upvotes: 1

Vagish
Vagish

Reputation: 2547

Is there a ways to define it somewhere without always include the header where it is defined?

NO.

You have to include header in each source file.

A normal practice is to have your own typdef.h. Define your own data types in it and include it in your source files of interest.

Upvotes: 1

Related Questions