在 Makefile.am C++库中编译 C 文件



我正在分叉Github上的一个现有项目,我想对其进行一些更改。我想做的一件事是添加一个额外的文件。此文件应位于 Makefile.am 生成的库之一中。问题是我要添加的文件是 .c 文件,而项目中的其他所有内容都是.cpp的。

应该包含该文件的库在生成文件中像这样使用:

MYLIBRARY=path/mylibrary.a
...
path_mylibrary_a_CPPFLAGS = $(AM_CPPFLAGS)
path_mylibrary_a_CXXFLAGS = $(AM_CXXFLAGS)
path_mylibrary_a_SOURCES = 
path/cppfile1.cpp 
path/cppfile1.h 
path/cppfile2.cpp 
path/cppfile2.h 
path/cppfile3.cpp 
path/cppfile3.h
...
mybinary_LDADD = $(MYLIBRARY)

简单地将path/cfile.cpath/cfile.h添加到源列表中会给我以下错误:

CXXLD    mybinary
/usr/bin/ld: path/mylibrary.a(path_mylibrary_a-cfile.o): relocation R_X86_64_32 against `.rodata' can not be used when making a shared object; recompile with -fPIC
path/mylibrary.a: error adding symbols: Bad value

我该怎么做,以便 Makefile.am 将编译 c 文件到一个原本用 c++ 构建的项目中?

解决此问题的规范方法是拥有一个方便的库,您可以在其中编译 c 代码:

path_mylibrary_a_LDADD = cfile.la
noinst_LTLIBRARIES = cfile.la
cfile_la_CPPFLAGS = -std=c11
cfile_la_SOURCES = cfile.c

有关更多信息,请参阅此答案。

我认为你的cfile.h有这样的结构

#ifndef MYLIBRARY_CFILE_H
#define MYLIBRARY_CFILE_H
#ifdef __cplusplus
extern "C" {
#endif
/* your C declarations here */
#ifdef __cplusplus
}
#endif
#endif /* MYLIBRARY_CFILE_H */

另外,作为一般提示:如果要将一些源文件添加到Makefile.am文件中的库或程序中,只需添加行

path_mylibrary_a_SOURCES += cfile.c cfile.h

这使得一个非常干净的补丁,只添加一行,不接触其他行等。

另外,我同意 https://stackoverflow.com/users/440558/some-programmer-dude 您可能还需要添加的path_mylibrary_a_CFLAGS

最新更新