【发布时间】:2015-04-11 23:07:19
【问题描述】:
我的任务是从对象文件创建存档文件 .a 并从存档 .a 文件创建共享库文件。我尝试使用以下文件进行实验:
foo.h
#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;
}
制作文件
CFLAGS = -Wall -Werror
LDFLAGS = -L/home/betatest/Public/implicit-rule-archive -Wl,-rpath,'$$ORIGIN'
all : run
run : main.o libfoo.so
$(CC) $(LDFLAGS) -o $@ $^
libfoo.so : CFLAGS += -fPIC # Build objects for .so with -fPIC.
libfoo.so : libfoo.a
$(CC) -shared -o $@ $^
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 $@ $<
#Include dependencies on subsequent builds.
.PHONY : all clean
clean :
-rm -f *.o *.d run libfoo.*
这个简单的测试程序似乎运行良好,但在编译时使用 make 它产生错误:
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 -
cc 在 $ORIGIN 周围得到文字单引号。尝试省略它们。
标签: c linux makefile shared-libraries