2012-03-15 wcdj
When there are many system modules, different developers may develop different modules, which may use the same definition. When each module is packaged as a static library for use by others, this is an implicit problem. If the same definition exists in different static libraries, which one do we use after compiling the link may not be what we want. The following is a simple example to illustrate the above problems:
// 1.c#include<stdio.h> void func(){ printf("1.c\n");}// 2.c#include<stdio.h> void func(){ printf("2.c\n"); } // main.c#include<stdio.h>int main(){ printf("main\n"); func();// which to call? return 0; }
Gcc-C 1.c
Gcc-C 2.c
Gcc-C main. c
Gcc-O test *. o
The LD linker links multiple target files. If the same definition is repeated, an error is returned.
Package the generated target file into a static library and try the link again:
Ar Cr lib1.a 1.o
Ar Cr lib2.a 2.o
Gcc-O test main. C-L.-L1-L2
In this case, the LD linker links based on the link sequence specified by humans. If lib1.a and lib2.a have duplicate definitions, the definitions in lib1.a are prioritized, the same definition (usually different implementations) in lib2.a will be ignored by lD.
Therefore, in multi-module development, we recommend that you use a namespace to display the called object to prevent this non-obvious trap error.
// 1.h#ifndef __C1__#define __C1__#include<stdio.h>namespace C1{ void func(); }#endif// 1.c#include "1.h"namespace C1{ void func() { printf("1.c\n"); }}// 2.h#ifndef __C2__#define __C2__#include<stdio.h>namespace C2{ void func(); }#endif// 2.c#include "2.h"namespace C2{ void func() { printf("2.c\n"); }}// main.c#include<stdio.h>#include "1.h"#include "2.h"using namespace C1;using namespace C2;int main(){ printf("main\n"); //func();// which to call? C1::func(); C2::func(); return 0;}
Through namespace, we can clearly specify the objects we want to use in semantics, so as to avoid the problem that was initially mentioned in this article. It can be seen that the establishment of good programming specifications is very important for large-scale projects, you can save time to locate bugs and enjoy beautiful music.