我在构建Makefile时遇到问题。我的主要文件是.cpp文件。在该文件中,有一个引用头文件helper_funcs.h的include。然后,此头文件声明各种函数,每个函数都在各自的.c文件中定义。我需要将.c文件编译为.o文件,将.o文件编译为helper_funcs库,然后当然能够从.cpp文件引用它们(我希望这样做是有意义的)。

这是我输入“make”时得到的:
g++ -Wall -O3 -o chessboard chessboard.cpp helper_funcs.a -framework OpenGL -framework GLUTld: warning: ignoring file helper_funcs.a, file was built for unsupported file format ( 0x2E 0x2F 0x2E 0x5F 0x43 0x53 0x43 0x49 0x78 0x32 0x32 0x39 0x2E 0x68 0x00 0x00 ) which is not the architecture being linked (x86_64): helper_funcs.a
编辑:
删除了先前的helper_funcs.a版本并重新编译后,上面的错误消失了,但这是结果:
g++ -Wall -O3 -o chessboard chessboard.cpp helper_funcs.a -framework OpenGL -framework GLUTUndefined symbols for architecture x86_64: "f1(char const*)", referenced from: _main in chessboard-MB9B95.old: symbol(s) not found for architecture x86_64clang: error: linker command failed with exit code 1 (use -v to see invocation)make: *** [chessboard] Error 1

LDFLAGS = -framework OpenGL -framework GLUT
CFLAGS = -c -g -Wall

all: chessboard

#  Generic compile rules
.c.o:
    gcc -c -O -Wall $<
.cpp.o:
    g++ -c -Wall $<

# Generic compile and link
%: %.c helper_funcs.a
    gcc -Wall -O3 -o $@ $^ $(LDFLAGS)

%: %.cpp helper_funcs.a
    g++ -Wall -O3 -o $@ $^ $(LDFLAGS)

#  Create archive
helper_funcs.a: f1.o f2.o
    ar -rcs helper_funcs.a $^

这是chessboard.cpp的开始:
#define GL_GLEXT_PROTOTYPES
#include "chessboard.h"
#include "helper_funcs.h"

using namespace std;

int main()
{
      // ...
      f1("arg");
      return 0;
}

helper_funcs.h:
#ifndef helper_funcs
#define helper_funcs

#include <stdio.h>
#include <stdlib.h>
#include <stdarg.h>
#include <string.h>
#include <math.h>

#ifdef USEGLEW
#include <GL/glew.h>
#endif
#define GL_GLEXT_PROTOTYPES
#ifdef __APPLE__
#include <GLUT/glut.h>
#else
#include <GL/glut.h>
#endif

void f1(const char* where);
void f2(const char* format , ...);

#endif

这是两个函数(显然,这些函数具有更多描述性的名称,但是我起初只是想比较笼统,所以我会坚持使用以避免混淆):

f1.c
#include "helper_funcs.h"

void f1(const char* where)
{
   // blah blah blah
}

f2.c
#include "helper_funcs.h"

void f2(const char* format , ...)
{
   // blah blah blah
}

最佳答案

在编译为C++的代码中,必须将函数f1f2声明为extern "C"。您可以在头文件中设置条件以提供该标记。

例如。

#ifdef __cplusplus
extern "C" {
#endif

void f1(const char* where);
void f2(const char* format , ...);

#ifdef __cplusplus
}
#endif

这样做的原因是,C++代码的编译方式是使函数经历一个名为“名称修改”的过程,以将完整的类型编码为链接器看到的符号,以实现跨编译单元的重载解析。 C编译器不这样做,因为C没有重载的概念。因此,当从C++代码调用C函数时,反之亦然,该函数必须声明为具有C样式的链接。

关于c++ - 无法使Makefile正常工作,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/19253383/

10-11 10:28