c++ - Makefile 编译 c 和 cpp 文件

标签 c++ c makefile

我想编译我的程序,但是我遇到了一些问题。我的程序由一个 main 函数组成,用 C 编写。其他文件是我没有编写的 .h 或 .cpp 文件。我有一个 make 文件,但不幸的是我无法编译我的程序。这是文件的“架构”:

a.h 只包含常量的定义。

b.h 和 b.cpp。 b.cpp 包括 a.h

c.h 和 d.cpp。 c.h 包含 d.cpp 方法的签名。 d.cpp包括a.h、b.h和c.h。

最后一个文件是main.c,其中包含c.h。

我使用的 makefile 如下:

CXX      = g++
CXXFLAGS = -Wall -ansi -g
CC       = gcc
CCFLAGS  = -g
OBJS     = main.o a.o b.o c.o

exec : $(OBJS)
    $(CXX) -o $@ $(OBJS)

c.o: d.cpp b.h a.h  
    $(CXX) -c $(CXXFLAGS) $<

a.o: a.h
    $(CXX) -c $(CXXFLAGS) $<

b.o: b.cpp a.h
    $(CXX) -c $(CXXFLAGS) $<

%.o : %.cpp
    $(CXX) -c $(CXXFLAGS) $<

%.o : %.c
    $(CC) -c $(CCFLAGS) $<

有人可以告诉我哪里错了吗?此外,如何修改 makefile 以便将 a、b、c 和 d 文件放入子文件夹中而不会造成任何问题?

谢谢!

编辑: 这是我得到的错误:

g++ -o tester main.o a.o b.o c.o
Undefined symbols for architecture x86_64:
    "_crypto_aead_encrypt", referenced from:
         _main in main.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [tester] Error 1

函数在c.h中声明,在d.cpp中定义

最佳答案

最可能的原因是,main 包含的 c.h 中的定义在编译 main.c 时被编译为 extern "C",但在编译到 d.cpp 中时被编译为 C++ extern(名称重整)。

(如果c.h是crypto_aead_encrypt函数的来源位置)

简单的解决方案是将所有内容编译为 C++(将 main 重命名为 .cpp,或者使用 ${CXX} 编译 main.c 并将“-x c++”添加到 CXXFLAGS)。

不太容易的解决方案需要在编译 d.cpp 时将 c.h 方法编译为 extern "C"- 这需要更改 c.h 和/或 d.cpp。或者为 c.h 中包含的 C++ 方法提供 C 包装器。

关于c++ - Makefile 编译 c 和 cpp 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35179191/

相关文章:

c++ - WebRTC 的 undefined reference

c++ - 在 C++ 中连接两个大文件

c++ - 模板递归区分 boot::tuple 中的数据类型

python - C++ 代码中递减运算符后的等号

检查 pthread mutex 是否被锁定或解锁(在线程锁定自身之后)

c++ - 当我用 gcc 替换 g++ 时,为什么我的 makefile 失败了?

ubuntu - 如何为 Code::Blocks 安装/使用 cbp2make?

c - "##"在 C 中做什么?

c - 无论如何,是否可以创建一个 if 语句来打印输出,说明我已经超出了多少公斤?

linux - Linux内核编译时输出的CC、LD、CC[M]等代码是什么?