如何构建仅使用 .h 文件的 c++ 程序

How to build a c++ program with only an .h file

本文关键字:文件 程序 c++ 何构建 构建      更新时间:2023-10-16

在GoogleTest的存储库中,有一个包含演示测试和文件的示例文件夹。在make文件夹中,有一个脚本来构建带有sample1.h的程序和sample1.cc文件(以及sample1_unittest.cc

# Builds a sample test.  A test should link with either gtest.a or
# gtest_main.a, depending on whether it defines its own main()
# function.
sample1.o : $(USER_DIR)/sample1.cc $(USER_DIR)/sample1.h $(GTEST_HEADERS)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1.cc
sample1_unittest.o : $(USER_DIR)/sample1_unittest.cc 
                     $(USER_DIR)/sample1.h $(GTEST_HEADERS)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample1_unittest.cc
sample1_unittest : sample1.o sample1_unittest.o gtest_main.a
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@

但是,示例文件夹中的第三个示例只有一个.h文件——sample3-inl.h其中包含所有测试的代码,即没有 .cc 文件。根据上面的例子,我试图像下面看到的那样构建它,但是当我运行时,它说sample3.o不存在

问:当所有代码都内联在.h文件中时,如果没有创建.o文件,如何构建程序?

 sample3.o : $(USER_DIR)/sample3-inl.h $(GTEST_HEADERS)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample3-inl.h
sample3_unittest.o : $(USER_DIR)/sample3_unittest.cc 
                     $(USER_DIR)/sample3-inl.h $(GTEST_HEADERS)
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample3_unittest.cc
sample3_unittest : sample3.o sample3_unittest.o gtest_main.a
    $(CXX) $(CPPFLAGS) $(CXXFLAGS) -lpthread $^ -o $@
sample3.o : $(USER_DIR)/sample3-inl.h $(GTEST_HEADERS)
  $(CXX) $(CPPFLAGS) $(CXXFLAGS) -c $(USER_DIR)/sample3-inl.h -o sample3.o

应该这样做。 如果没有上述更改,代码将在sample3.o规则中生成sample3-inl.o

或者稍后将输入.o文件更改为 sample3-inl.o