我得到了一個任務,從對象文件創建歸檔文件.a,並從歸檔.a文件創建共享庫文件。我已經試過有實驗以下文件:
foo.h中來自存檔(.a)文件的共享庫C
#ifndef _foo_h__
#define _foo_h__
extern void foo(void);
extern void bar(void);
#endif //_foo_h__
foo.c的
#include<stdio.h>
void foo(void)
{
puts("Hello, I'm a shared library");
}
bar.c
#include<stdio.h>
void bar(void)
{
puts("This is bar function call.");
}
的main.c
#include <stdio.h>
#include"foo.h"
int main(void)
{
puts("This is a shared library test...");
foo();
bar();
return 0;
}
的Makefile
CFLAGS = -Wall -Werror
LDFLAGS = -L/home/betatest/Public/implicit-rule-archive -Wl,-rpath,'$$ORIGIN'
all : run
run : main.o libfoo.so
$(CC) $(LDFLAGS) -o [email protected] $^
libfoo.so : CFLAGS += -fPIC# Build objects for .so with -fPIC.
libfoo.so : libfoo.a
$(CC) -shared -o [email protected] $^
libfoo.a : foo.o bar.o
ar cvq libfoo.a foo.o bar.o
# ar cr libfoo.a foo.o bar.o
# Compile any .o from .c. Also make dependencies automatically.
%.o : %.c
$(CC) -c $(CFLAGS) -o [email protected] $<
#Include dependencies on subsequent builds.
.PHONY : all clean
clean :
-rm -f *.o *.d run libfoo.*
這個簡單的測試程序似乎運行正常,但在使用使其產生錯誤的編譯:
cc -c -Wall -Werror -o main.o main.c
cc -c -Wall -Werror -fPIC -o foo.o foo.c
cc -c -Wall -Werror -fPIC -o bar.o bar.c
ar cvq libfoo.a foo.o bar.o
a - foo.o
a - bar.o
cc -shared -o libfoo.so libfoo.a
cc -L/home/betatest/Public/implicit-rule-archive -Wl,-rpath,'$ORIGIN' -o run main.o libfoo.so
main.o: In function `main':
main.c:(.text+0xf): undefined reference to `foo'
main.c:(.text+0x14): undefined reference to `bar'
collect2: ld returned 1 exit status
Makefile-test:7: recipe for target 'run' failed
make: *** [run] Error 1
有人請指出我在哪裏出錯?非常感謝。
你不鏈接共享庫:嘗試' -lfoo'而不是'libfoo.so' – 2015-02-11 14:29:46
cc正在獲取$ ORIGIN附近的文字單引號。嘗試省略它們。 – 2015-02-11 14:34:48