我的C++頭是C包裝爲C++類返回不正確的地址
header.hh
#include <stdint.h>
#include <stdio.h>
#ifdef __cplusplus
#include <string>
class A
{
uint32_t a;
public:
A(){
a = 0;
}
void update(uint32_t b) {
a = b;
}
};
#else
typedef struct A A;
#endif //__cplusplus
#ifdef __cplusplus
extern "C" {
void* newA(void);
void deleteA(A* a);
void update(A*a,uint32_t b);
}
#endif
而我的C++文件是
class.cc
#include "header.hh"
#include <iostream>
extern "C" {
void* newA(void) {
A* a = new A();
return (reinterpret_cast <void*> (a));
}
void deleteA(A* a) {
delete a;
}
void update(A* a,uint32_t b){
a->update(b);
}
}
main.c中
#include "header.hh"
#include <stdio.h>
int main()
{
A* a = (A*) newA();
deleteA(a);
}
的Makefile
CFLAGS=-Wall -g -ansi -pedantic -std=c99
CCFLAGS=-Wall -g
LDFLAGS=-g -Wall -lstdc++
OBJS=class.o main.o
PROG=test
all:$(PROG)
default: all
%.o: %.cc
$(CC) $(CCFLAGS) -c $<
%.o: %.c
$(CC) $(CFLAGS) -c $<
$(PROG): $(OBJS)
$(CC) $(OBJS) $(LDFLAGS) -o [email protected]
clean:
rm -rf $(OBJS)
rm -rf $(PROF)
當我編譯並運行這個程序,我看到了段錯誤,當我嘗試調用主析構函數。
我走進GDB,發現地址「一」在class.cc是0x7fff980097a0並在主要是0xffffffff980097a0。
什麼導致地址被改變?
我在ubuntu 14.04上使用gcc的4.8.4版本。
順便說一句,你可能會返回'A的*'代替'無效*'爲'newA'。 – Jarod42