靜態鏈接
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所在的目錄路徑,即寫入項目的頭文件目錄。
最後,點擊編譯即可。