如何在实践中解决链接库在项目编译中的顺序

时间:2015-11-27 02:51:25

标签: c++ c gcc makefile libraries

我一直在研究一个项目,该项目使用来自许多作者(物理学)的不同来源和代码,我想将它们合并在一起并在它们之间进行通信。 问题是这些源和makefile中的一些首先调用链接库,然后调用c文件:

$(CC) $(lflags) -o smith2demo smith2demo.o smith2.o

到目前为止,在我所研究所的计算机和其他一些系统中,一切正常。我有这个gcc编译器:

$gcc --version
gcc (Debian 4.9.2-10) 4.9.2
Copyright (C) 2014 Free Software Foundation, Inc.

所以,在我尝试在Ubuntu上运行代码之前,我没有注意到这个问题:

gcc (Ubuntu 4.9.3-5ubuntu1) 4.9.3
Copyright (C) 2015 Free Software Foundation, Inc.

在ubuntu中,我得到的结论是:

smith2.c:(.text+0x29b): undefined reference to `sincos'

我知道链接库规范及其原因,请在此处解答:

GCC C++ Linker errors: Undefined reference to 'vtable for XXX', Undefined reference to 'ClassName::ClassName()'

Why does the order in which libraries are linked sometimes cause errors in GCC?

Why am I getting a gcc "undefined reference" error trying to create shared objects?

所以,我有两个问题:

为什么两个gcc都是最新版本,我在Debian系统中没有这个问题?

如何在没有告诉他们更改C文件之前调用库的所有makefile的情况下,如何将此代码分发给其他人?

在我的项目中的大多数情况下,我使用整体Makefile,然后我只需更改到源文件夹并在那里执行$(MAKE)

有没有办法将--no-as-needed一般设为每个人的选项或更聪明的方式?

我对makefile很少有经验。

1 个答案:

答案 0 :(得分:0)

在我的个人生活中,我使用自己的Makefile。这是更简单的版本。

    MAIN = main
    HEADER_DEFINITIONS = fibo
    CC = g++-4.9 -std=c++11
    COMPILE = -c
    EXE = $(MAIN)
    OPTIMIZE = -Os
    SHELL = /bin/bash
    ARGS = 20
    all: link
    @echo "Executing..........."
    @echo " > > > > > > OUTPUT < < < < < < "
    @$(SHELL) -c './$(EXE) $(ARGS)'
    link: compile
    @echo -n "Linking............."
    @$(SHELL) -c '$(CC) -o $(EXE) *.o'
    compile: $(MAIN).cpp $(HEADER_DEFINITIONS).cpp
    @echo -n "Compiling........."
    @$(SHELL) -c '$(CC) $(OPTIMIZE) $(COMPILE) $^'
    clean:
    @echo "Cleaning............"
    @$(SHELL) -c 'rm -f *~ *.o $(EXE)'

如果要进一步修改和添加某些链接器标志,则完全可以

编辑2 我的个人Makefile

#
# A simple makefile for managing build of project composed of C source files.
#


# It is likely that default C compiler is already gcc, but explicitly
# set, just to be sure
CC = gcc

# The CFLAGS variable sets compile flags for gcc:
#  -g        compile with debug information
#  -Wall     give verbose compiler warnings
#  -O0       do not optimize generated code
#  -std=c99  use the C99 standard language definition
#  -m32      CS107 targets architecture IA32 (32-bit)
CFLAGS = -g -Wall -O0 -std=c99 -m32

# The LDFLAGS variable sets flags for linker
#  -lm   says to link in libm (the math library)
LDFLAGS = -lm

# In this section, you list the files that are part of the project.
# If you add/change names of source files, here is where you
# edit the Makefile.
SOURCES = demo.c vector.c map.c
OBJECTS = $(SOURCES:.c=.o)
TARGET = demo


# The first target defined in the makefile is the one
# used when make is invoked with no argument. Given the definitions
# above, this Makefile file will build the one named TARGET and
# assume that it depends on all the named OBJECTS files.

$(TARGET) : $(OBJECTS)
    $(CC) $(CFLAGS) -o $@ $^ $(LDFLAGS)


.PHONY: clean

clean:
    @rm -f $(TARGET) $(OBJECTS) core