4

我的问题很简单,但我只是不知道如何解决它。如果我不使用 make 文件,我知道如何编译、库和链接它,因为这样我就可以单独调用 ar 并且一切正常。

无论如何,我正在使用petsc库,并且正在使用他们提供的 makefile:

CFLAGS          = 
FFLAGS          = 
CPPFLAGS        = 
FPPFLAGS        =
LOCDIR          = /home/user/.../.../   # Working folder
EXAMPLESC       = main.cpp class.cpp        #.cpp file names here
EXAMPLESF       =
#MANSEC          = Mat I don't know what this is but it seems to work without it.

include ${PETSC_DIR}/conf/variables
include ${PETSC_DIR}/conf/rules

myProgram: main.o class.o  chkopts
    -${CLINKER}  -o myProgram main.o class.o ${PETSC_MAT_LIB}
    ${RM} main.o class.o

include ${PETSC_DIR}/conf/test

ARFLAGS 将 -rv 作为默认值,所以我应该在哪里提供这样的信息

ar -rv libclassdll.a class.o

我应该在哪里添加 -L./-lclassdll ?

我是makefile的新手,所以我在这里有点迷路:<

我试图将线路更改为

myProgram: main.o class.o  chkopts
    -${CLINKER}  -o myProgram main.o class.o ${AR} libclassdll.a class.o ${PETSC_MAT_LIB}
    ${RM} main.o class.o

然后我的编译命令似乎是 mpicxx -o myProgram main.o class.o /usr/bin/ar/libclassdll.a class.o -L (这里有很多链接),至少它说: g++ classdll.a没有这样的文件或目录。

所以它甚至不会为我生成一个 lib 文件。所以任何想法都会非常感激。

当我在不同的机器上上传 makefile 时的一个新问题,我当前的 makefile 看起来像这样

LibMyClass.so: MyClass.o  chkopts
    -${CLINKER}  -shared -Wl,-soname,${SONAME} -o ${VERS}   *.o  ${PETSC_MAT_LIB}

    mv ${VERS} ${LIBADD}
    ln -sf ${LIBADD}${VERS} ${LIBADD}${SOWOV}
    ln -sf ${LIBADD}${VERS} ${LIBADD}${SONAME}

这适用于一台机器,但另一台机器出现以下错误

/usr/bin/ld: MyClass.o: relocation R_X86_64_32S against `.rodata' can not be used when making a shared object; recompile with -fPIC
MyClass.o: could not read symbols: Bad value

当然,我确实更改了路径,但我想这表明存在其他类型的问题,因为即使我输入“g++ -shared -Wl,-soname,libmyclass.so.1 -o libmyclass.so.1.0 MyClass.o”或“g++” -fPIC -share..." 我会得到同样的错误。

4

2 回答 2

6

理想情况下,您应该首先构建库,然后使用它,就像“手动”一样。

要构建(或更新)库,您需要这样的规则:

libclassdll.a: class.o
    ar -rv libclassdll.a class.o

或者更简洁,像这样:

libclassdll.a: class.o
    ar $(ARFLAGS) $@ $^

那么规则就myProgram变成了:

# Assuming CLINKER is something civilized, like gcc
myProgram: main.o libclassdll.a  chkopts
    -${CLINKER} -o myProgram main.o -L. -lclassdll ${PETSC_MAT_LIB}

或更好:

myProgram: main.o libclassdll.a  chkopts
    -${CLINKER} -o $@ $< -L. -lclassdll ${PETSC_MAT_LIB}

所以在你的makefile中,你会替换

myProgram: main.o class.o  chkopts
    -${CLINKER}  -o myProgram main.o class.o ${PETSC_MAT_LIB}
    ${RM} main.o class.o

myProgram: main.o libclassdll.a  chkopts
    -${CLINKER} -o $@ $< -L. -lclassdll ${PETSC_MAT_LIB}

libclassdll.a: class.o
    ar $(ARFLAGS) $@ $^

您还可以进行其他改进,但现在应该足够了。

于 2012-03-06T23:35:48.633 回答
3

使 myProgram 依赖于 main.o 和 libclass.a(不要称它为 libclassdll.a;它不是 DLL,而是静态库)。

解决方案的一般要点:

# $@ means "the target of the rule"
# $^ means "the prerequisites: main.o and libclass.a"

myProgram: main.o libclass.a
        $(CC) -o $@ $^ # additional arguments for other libraries, not built in this make

libclass.a: class.o
        # your $(AR) command goes here to make the library
于 2012-03-06T23:26:00.357 回答