0

I build two libraries called templib1.a and templib2.a

And some global variables and function names in templib1.a and templib2.a are the same; when I try to compile my c code with these two libraries, it failed.

Is there any method except namespace for solving this problem? Do I need to re-build the libraries? Thanks.

=======================================================================

I build libraries as following

build templib1.a from aaa.c bbb.c ddd.c aaa.h; there is global variable int var_a, int var b; and functions void func_a(), void func_b() in aaa.c and bbb.c respectively

build templib2.a from aaa.c bbb.c eee.c aaa.h; there is global variable int var_a, int var b; and functions void func_a(), void func_b() in aaa.c and bbb.c respectively

And I my c code like

gcc $(INC) $(TEMPLIB1_DIR)/templib1.a $(TEMPLIB2_DIR)/temp2lib.a -o run

and it shows

"multiple definition of var_a temp2lib.a : first defined here"

"multiple definition of var_b temp2lib.a : first defined here"

2 Answers2

1

Judging by the names of your libs, object files and variables, this is only a toy lib. When you write a real lib, you have to think about its design:

  • Under Unix, it is customary to name your lib libsomething.a. Your libs should therefore be called libtemp1.a and libtemp2.a, so that you can easily link them with -ltemp1 and -ltemp2.

  • If you export all symbols, you'll probably export too much and therefore clutter the namespace available for link symbols.

  • Think about which symbols you should export. The user of the lib needs to know which symbols she can use, so there's probably a header file accompanying the lib. This is the lib's interface. You need to export only the symbols in that interface. Start by making as many global variables and functions static, i.e. local to one compilation unit (object file). If you still export too many symbols, consider controlling your exports manually.

  • C doesn't have packages or namespaces. It is good practice to prefix all exported symbols with a short prefix, e.g. temp1_var_a, temp1_initi and so on.

  • Choose meaningful names for your symbols. A global variable shouldn't be called var_a. Use this rule of thumb: Small scope, short names. Big scope, longer names.

  • Don't be shy to rebuild your libs if you are their only user.

Community
  • 1
  • 1
M Oehm
  • 28,726
  • 3
  • 31
  • 42
1

If your want your functions and variables accessible from outside your libs, rename them and include prefix.

If those functions and variables are for internal use only, use the static keyword:

What does "static" mean?

Community
  • 1
  • 1
Nagi
  • 256
  • 1
  • 2
  • 4
  • If one variable is internal used for templib1.a; aaa.c and bbb.c must use this vairable. Can I use static int var_ab in aaa.c and extern static int var_ab in bbb.c ? – user3737017 Jun 13 '14 at 11:12
  • Have you tried with a simpler solution: declare static int var_ab in a header file? – Nagi Jun 14 '14 at 18:04