gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:32:36 26 4
gpt4 key购买 nike

我想编译我的程序,但是我遇到了一些问题。我的程序由一个 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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com