问题描述
我有一个简单的 C 程序。 我正在尝试在其中使用 libarchive。 问题是链接器可能无法正常工作,所以我可以只包含 archive.h 标头而不会出错,但无法在应用程序内使用任何方法,因为我收到未定义的引用错误。 这是我的代码:
#include <stdio.h>
#include <archive.h>
#include <archive_entry.h>
#include <fcntl.h>
#include <dirent.h>
#include <string.h>
int main(){
return 0;
}
write_archivec(const char *outname,const char *inner,const char **ls1,const char **ls2)
{
struct archive *a;
struct archive_entry *entry;
struct stat st;
char buff[8192];
int len;
int file;
a = archive_write_new();
archive_write_add_filter_gzip(a);
archive_write_set_format_pax_restricted(a); // Note 1
archive_write_open_filename(a,outname);
while (*ls1)
{
char tem[80];
strcpy(tem,inner);
strcat(tem,"/");
//tem = (char*)realloc(tem,strlen("symlinkpath"));
strcat(tem,*ls2);
stat(*ls1,&st);
entry = archive_entry_new(); // Note 2
archive_entry_set_pathname(entry,&tem);
archive_entry_set_size(entry,st.st_size); // Note 3
archive_entry_set_filetype(entry,AE_IFREG);
archive_entry_set_perm(entry,0644);
archive_write_header(a,entry);
file = open(*ls1,O_RDONLY);
if(file == -1){
void Unlock();
}
len = read(file,buff,sizeof(buff));
while (len > 0)
{
archive_write_data(a,len);
len = read(file,sizeof(buff));
}
close(file);
archive_entry_free(entry);
ls1++;
ls2++;
}
archive_write_close(a);
archive_write_free(a);
}
输出将是:
$ gcc -I/usr/local/include -L/usr/local/lib -larchive t.c -o a
/usr/bin/ld: /tmp/cclrnMld.o: in function `write_archivec':
t.c:(.text+0x62): undefined reference to `archive_write_new'
/usr/bin/ld: t.c:(.text+0x78): undefined reference to `archive_write_add_filter_gzip'
/usr/bin/ld: t.c:(.text+0x87): undefined reference to `archive_write_set_format_pax_restricted'
/usr/bin/ld: t.c:(.text+0xa0): undefined reference to `archive_write_open_filename'
/usr/bin/ld: t.c:(.text+0x12f): undefined reference to `archive_entry_new'
/usr/bin/ld: t.c:(.text+0x14f): undefined reference to `archive_entry_set_pathname'
/usr/bin/ld: t.c:(.text+0x168): undefined reference to `archive_entry_set_size'
/usr/bin/ld: t.c:(.text+0x17c): undefined reference to `archive_entry_set_filetype'
/usr/bin/ld: t.c:(.text+0x190): undefined reference to `archive_entry_set_perm'
/usr/bin/ld: t.c:(.text+0x1a9): undefined reference to `archive_write_header'
/usr/bin/ld: t.c:(.text+0x211): undefined reference to `archive_write_data'
/usr/bin/ld: t.c:(.text+0x258): undefined reference to `archive_entry_free'
/usr/bin/ld: t.c:(.text+0x28a): undefined reference to `archive_write_close'
/usr/bin/ld: t.c:(.text+0x299): undefined reference to `archive_write_free'
collect2: error: ld returned 1 exit status.
我也按照这里的安装说明
解决方法
因为 archive_...
函数不是标准的 C,所以你需要明确地告诉编译器它可以在哪里找到库。
您通常使用 -l
编译器标志执行此操作。您可以使用 -L
标志来指定库的路径。检查编译器的文档。
但您也可以通过指定库的完整路径来显式链接库。
要回答的第一个问题是:您的库安装在哪里?
,大多数是我的错误还是 gcc 的错误?
我发现我应该在文件名后指定链接和包含参数 所以:
$ gcc -I/usr/local/include -L/usr/local/lib -larchive t.c -o a
should replaced with:
$ gcc t.c -I/usr/local/include -L/usr/local/lib -larchive -o a