静态链接 1.建立静态链接库 File→New→Project→Static library
示例: 建立静态链接库工程:StaticLibrary,
static.h
#ifndef STATIC_H_INCLUDED
#define STATIC_H_INCLUDED
#ifdef __cplusplus
extern "C"
{
#endif
int SampleAddInt(int i1, int i2);
void SampleFunction1();
int SampleFunction2();
#ifdef __cplusplus
}
#endif
#endif // STATIC_H_INCLUDED
static.c
// The functions contained in this file are pretty dummy
// and are included only as a placeholder. Nevertheless,
// they *will* get included in the static library if you
// don't remove them :)
//
// Obviously, you 'll have to write yourself the super-duper
// functions to include in the resulting library...
// Also, it's not necessary to write every function in this file.
// Feel free to add more files in this project. They will be
// included in the resulting library.
#include "static.h"
// A function adding two integers and returning the result
int SampleAddInt(int i1, int i2)
{
return i1 + i2;
}
// A function doing nothing ;)
void SampleFunction1()
{
// insert code here
}
// A function always returning zero
int SampleFunction2()
{
// insert code here
return 0;
}
工程文件包括static.h和static.c,具体如下,然后编译工程,会生成一个libStaticLibrary.a文件。 libStaticLibrary.a是用于链接的,与其他文件一起编译生成一个exe执行文件。
2.建立主工程 建立Console application
将生成一个main.c示例文件,在最上方添加#include "static.h"语句,这样就可以调用静态链接库里的函数了。
#include <stdio.h>
#include <stdlib.h>
#include "static.h"
int main()
{
int a = 1, b = 2;
printf("a + b = %d\n", SampleAddInt(a, b));
printf("Hello world!\n");
return 0;
}
然后选择菜单栏Project->Build Options,弹出Project Build Options,选择工程名称。在Linker settings选项卡下添加libStaticLibrary.a的路径,即添加需要的库。
在Search directories选项卡下的Compiler子选项卡下添加static.h所在的目录路径,即写入项目的头文件目录。
最后,点击编译即可。