Maxthecat
Maxthecat

Reputation: 1328

Using enums from statically linked libraries

I've seen that enums do not get exported from libraries in gcc. That is, if I have enum foo in lib1.c and use it to build lib.a, I cannot use enum foo in myprog.c, which links against the library.

As such, does that mean that if I want to use enum foo, I have to redefine it in myprog.c? Also, is there any way to export the enums for a library so that my program can make use of them?

Upvotes: 0

Views: 604

Answers (2)

nos
nos

Reputation: 229184

This is what you do:

Create one (or more) header files that contains the declaration for lib1.c that you want other code to be able to use:

lib1.h:

#ifndef LIB1_H_
#define LIB1_H_

enum Foo {
    Bar =1
};

void do_something(enum Foo a);

#endif

In the lib1.c source code, you include this header file, use the enum you defined, and implement the do_something() function.

Build lib1.c to produce your library, lib1.a

Anyone that wants to use your lib1.a needs two thing:

  • The library, lib1.a
  • The lib1.h header file for the library.

The source code that need to use functionality from lib1.a, include the same headerfile lib1.h , where the enum, functions, and other things are declared, and you link to the lib1.a

Upvotes: 1

Damon
Damon

Reputation: 70186

This is "normal behavior". Enums are compile-time constants, not variables that are put in a binary or exported.

Typically, when using a library, you would include a header file with the definitions of the functions that you will use and the enumerations used in/with this library.

Upvotes: 1

Related Questions