【问题标题】:Link .h files and .c files from different directory using makefile使用 makefile 链接来自不同目录的 .h 文件和 .c 文件
【发布时间】:2016-04-03 03:20:56
【问题描述】:

我正在尝试使用 um.c 从当前文件夹中编译一个名为 um 的程序 并包括一些外部实现。 .h 文件位于一个目录中,但实现这些 .h 文件的 .c 文件位于不同的目录中。下面是我的makefile。编译器似乎知道在哪里查找 .h 文件。但是,链接器失败并产生错误:

ld: symbol(s) not found for architecture x86_64
clang: fatal error: linker command failed with exit code 1

生成文件:

# define the C compiler to use
CC = gcc

# define any compile-time flags
CFLAGS = -g -O -Wall -Wextra -Werror -Wfatal-errors -std=c99 -pedantic

# define any directories containing header files other than /usr/include
INCLUDES = -I/Users/nguyenmanhduc/Documents/C\ library/cii/include

# define library paths in addition to /usr/lib
LFLAGS = -L/Users/nguyenmanhduc/Documents/C\ library/cii/src

# define any libraries to link into executable:
LIBS = -lm

# define the C source files
SRCS = um.c

# define the C object files 
OBJS = $(SRCS:.c=.o)

# define the executable file 
MAIN = um

.PHONY: depend clean

all:    $(MAIN)
    @echo  Simple compiler named um has been compiled

$(MAIN): $(OBJS) 
    $(CC) $(CFLAGS) $(INCLUDES) -o $(MAIN) $(OBJS) $(LFLAGS) $(LIBS)

.c.o:
    $(CC) $(CFLAGS) $(INCLUDES) -c $<  -o $@

clean:
    $(RM) *.o *~ $(MAIN)

depend: $(SRCS)
    makedepend $(INCLUDES) $^

这个问题可能看起来很奇怪,因为我对 makefile 几乎没有经验,但是有没有办法可以使用 makefile 链接不同文件夹中的 .h 和 .c 文件。

谢谢!

【问题讨论】:

    标签: c++ c makefile linker


    【解决方案1】:

    这里的问题不在于您的其他 .c 文件位于不同的目录中:而是您没有告诉您的 Makefile 它们存在

    这里是你列出源输入的地方(我猜你没有看到评论?):

    # define the C source files
    SRCS = um.c
    

    添加其他 .c 文件,其编译后的 .os 是您要链接的内容。

    例如:

    # define the C source files
    SRCS = um.c ../wot.c ../hah/lol.c
    

    没有硬性规定,但是,按照您构建此 Makefile 的方式,这些相对路径应该可以很好地解析。

    【讨论】:

      【解决方案2】:

      你不链接.c文件,你链接.o文件。

      您似乎在说您的某些 .c 文件位于不同的目录中。

      不管怎样,你必须在你的makefile中明确列出那些.c文件,就像你在makefile目录中列出.c文件一样。您必须在不同的目录中编译.c 文件,然后链接它们,就像您在与makefile 相同的目录中编译和链接.c 文件一样。他们不会自己编译。

      另一种方法是在另一个目录中有一个单独的 makefile,它编译和构建一个存档库,然后在这个目录中与该存档库链接。

      【讨论】:

        猜你喜欢
        • 2017-08-13
        • 2015-10-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多