【问题标题】:-I flag in the makefile does not result in a header file being found (gtest/gtest.h)makefile 中的 -I 标志不会导致找到头文件 (gtest/gtest.h)
【发布时间】:2016-11-15 08:58:20
【问题描述】:

以前我一直在努力在根目录中创建一个生成文件,该文件将处理src 文件夹中的源文件和include 文件夹中的标题。在此之后,我想添加另一个文件夹 tests,我将在其中保存带有测试的 .cpp 文件。不幸的是,我遇到了这个问题。

文件夹结构为:

.
|__makefile
|
|__/src
|  |
|  |__[regular .cpp files]
|
|__/include
|  |
|  |__[.h files]
|  |
|  |__/gtest
|     |
|     |__gtest.h
|
|__/tests
   |
   |__test_factorial.cpp

./tests/test_factorial.cpp:

#include "gtest/gtest.h"
#include "factorial.h"

// some tests

制作文件:

CC = g++

CFLAGS = -Wall

INCLUDES = -I./include

LIBS = -lgtest -lpthread

SOURCEDIR = ./src/
SRCS = $(shell find ./src/ -name '*.cpp')
SRCS += $(shell find ./tests/ -name '*.cpp')

.PHONY: clean depend

SRCS := $(filter-out ./tests/main_tests.cpp, $(SRCS))
OBJS = $(SRCS:.cpp=.o)
OBJS := $(OBJS:./src%=.%)

release: $(OBJS)
        $(CC) $(CFLAGS) -o app $(OBJS) $(LIBS)

VPATH = ./src:./tests

%.o: ./src/%.cpp
        $(CC) $(CFLAGS) $(INCLUDES) -c ./src/$*.cpp

%.o: ./tests/%.cpp
        $(CC) $(CFLAGS) $(INCLUDES) -c ./tests/$*.cpp

depend: .depend

.depend: $(SRCS)
        rm -f ./.depend
        $(CC) $(CFLAGS) $(INCLUDES) -MM $^ > ./.depend;

include .depend

当我从根目录执行make 时,/src 中的所有文件都可以正常编译(我最终在根目录中为它们提供了目标文件),但是 /tests 目录中的 .cpp 文件出现错误:

g++    -c -o tests/test_factorial.o tests/test_factorial.cpp
tests/test_factorial.cpp:1:25: fatal error: gtest/gtest.h: No such file or directory
compilation terminated.
<builtin>: recipe for target 'tests/test_factorial.o' failed
make: *** [tests/test_factorial.o] Error 1

重要的是,.depend 文件似乎没问题:

test_factorial.o: tests/test_factorial.cpp include/gtest/gtest.h \
 include/factorial.h

makefile 出了什么问题?

编辑

我相信这个错误片段:

<builtin>: recipe for target 'tests/test_factorial.o' failed

表明makefile的这部分有问题:

%.o: ./src/%.cpp
        $(CC) $(CFLAGS) $(INCLUDES) -c ./src/$*.cpp

%.o: ./tests/%.cpp
        $(CC) $(CFLAGS) $(INCLUDES) -c ./tests/$*.cpp

为什么它试图做./tests/test_factorial.o而不是./test_factorial.o?让我再次强调一下,./src/*.cpp 文件的目标文件最终位于根目录中,即./*.o,而不是./src/*.o

【问题讨论】:

  • 标题完全错误,实际构建输出显示没有 -I 选项被传递给 g++

标签: c++ makefile


【解决方案1】:

您的 makefile 正在构建中

tests/test_factorial.o

来自

tests/test_factorial.cpp

这不符合规则

%.o: ./tests/%.cpp

所以它改为使用内置规则。 (顺便说一句,惯例是使用$(CXX)$(CXXFLAGS) 而不是$(CC) 构建c++ 文件。

尝试以下规则模式

./tests/%.o: ./tests/%.cpp

您的 Makefile 使用名称 tests/test_factorial.o 的原因是因为

OBJS = $(SRCS:.cpp=.o)

这(应该很明显)使.o 文件的路径与.cpp 的路径相同。

您有一个后续规则剥离路径src/

OBJS := $(OBJS:./src%=.%)

tests/ 没有类似的规则

【讨论】:

  • 啊!是的...一个简单的遗漏...我刚刚添加了 OBJS := $(OBJS:./tests%=.%) 并且一切正常。谢谢。
猜你喜欢
  • 1970-01-01
  • 2021-05-08
  • 2015-10-11
  • 2015-12-24
  • 2021-07-14
  • 2013-09-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多