使用靜態庫的時候,gcc編譯出來的靜態鏈接庫g++編譯代碼的時候有時候鏈接不了,而g++編譯的靜態鏈接庫gcc在編譯的時候有時候也使用不了。
下面舉例說明:
編寫庫文件:
hello.h
#ifndef HELLO_H_
#define HELLO_H_
#include <stdio.h>
void HelloFunc();
#endif /*HELLO_H_*/
hello.c
#include "hello.h"
void HelloFunc()
{
printf("Hello World!\n");
}
hello.cc
#include "hello.h"
void HelloFunc()
{
printf("Hello World!\n");
}
測試代碼:
main.c
#include <stdio.h>
int main() {
printf("Hello World!\n");
return 0;
}
main.cc
#include <stdio.h>
int main() {
printf("Hello World!\n");
return 0;
}
test.c
#include "hello.h"
int main()
{
HelloFunc();
return 0;
}
test.cc
#include "hello.h"
int main()
{
HelloFunc();
return 0;
}
Makefile
gcc -o Test test.cc -I.../include/ -L.../lib/ -lhello
gcc -o Test test.c -I.../include/ -L.../lib/ -lhello
g++ -o Test test.cc -I.../include/ -L.../lib/ -lhello
g++ -o Test test.c -I.../include/ -L.../lib/ -lhello
gcc main.c
gcc main.cc
g++ main.c
g++ main.cc
結論:
1.gcc編譯hello.c形成libhello.a
gcc | test.c | 正確 |
gcc | test.cc | 錯誤 |
g++ | test.c | 錯誤 |
g++ | test.cc | 錯誤 |
2.g++編譯hello.cc形成libhello.a
gcc | test.c | 錯誤 |
gcc | test.cc | 正確 |
g++ | test.c | 正確 |
g++ | test.cc | 正確 |
3.gcc編譯hello.c形成libhello.so
gcc | test.c | 正確 |
gcc | test.cc | 錯誤 |
g++ | test.c | 錯誤 |
g++ | test.cc | 錯誤 |
4.g++編譯hello.cc形成libhello.so
gcc | test.c | 錯誤 |
gcc | test.cc | 正確 |
g++ | test.c | 正確 |
g++ | test.cc | 正確 |
建議:
使用g++編寫靜態鏈接庫和動態鏈接庫