【问题标题】:one header for some .c files leads to linker error某些 .c 文件的一个标头会导致链接器错误
【发布时间】:2013-01-29 21:12:49
【问题描述】:

我的设置是这样的:

src/
  dir1/
    header.h
    dir11
      (several files, every including header.h)
  dir2/
  (and so on)

但是链接器告诉我undefined reference to (the function which is defined in the subdir "dir11")。标题如下所示:

#ifndef header_h
#define header_h

/* some includes, all protected via ifndef-define-endif */

/* function prototypes for all functions in the 'dir11' subdir */
#endif // header_h

生成文件:

# some variables are defined before...

TARGET=mytarget 
SOURCES= ${shell find ${SRC} -type f -name '*.c'} 
OBJECTS=${foreach x, $(basename $(SOURCES)), $(x).o}

compile: ${OBJECTS}

%.o: %.c 
        ${CC} -c ${CFLAGS} ${HEADERS} $^ -o $@

link:
        ${LD} ${OBJECTS} -o ${TARGET}

如何解决这个问题?为子目录中的每个文件编写标头是我想要走的最后一条路,因为其中有大约 50 个文件!

编辑: 也许这很有用:header.h 也包含在其他地方以调用函数!当包含 elsewere 时,我是否必须将此函数声明为 extern

【问题讨论】:

  • "未定义的引用"... 什么?我希望那是一个错字,你的意思是 #ifndef 在那个头文件的顶部。 #ifdef 会有点毫无意义(并且会阻止任何内容包含在其中)。
  • 你的包含保护错了吗?不应该是#ifndef header_h吗?
  • 嗯,是的,这是一个错字。对函数的未定义引用,这些函数在子目录的.c 文件中定义。 (我将在问题帖子中对此进行编辑!)
  • 所以它是一个未定义的引用,而不是链接处的未已解决引用?如果在编译时,您 not 会遇到 cannot-find-include-file "blah" 编译错误吗?另外,神奇的 ${HEADERS} 宏扩展成什么?
  • 标头宏扩展为-I./src。编译工作没有错误(除了一些 -Wunused-function 警告)!

标签: c header linker makefile


【解决方案1】:

所有包含保护的定义都不同吗?如果不是,您将收到未定义的参考警告/错误,具体取决于您的编译器设置

【讨论】:

  • 是的,他们是。总是__<projectname>_<filename>_H__!
  • 只要确保你的头文件没有同名
  • 你读过我写的吗?它们在每个文件中不同!
  • 抱歉,只是想找出您的问题。
猜你喜欢
  • 2011-10-27
  • 1970-01-01
  • 2020-10-09
  • 2017-02-03
  • 1970-01-01
  • 2013-07-09
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
相关资源
最近更新 更多