Oct 21, 2009 at 9:22am UTC
Hello,
i'm trying to call a C method in C++ code and i have some difficulties about it.
let me explain it with code samples:
my .h header file.
#ifndef X_MODULE_H_
#define X_MODULE_H_
#include <stdio.h>
#ifdef __cplusplus
extern "C"
{
#endif
int printStatus();
#ifdef __cplusplus
}
#endif
#endif /*X_MODULE_H_*/
my .c implementation file
#include "X_Module.h"
int printStatus()
{
printf("printStatus is called\n");
return 1;
}
my main.cpp file
#include <iostream>
using namespace std;
extern "C"
{
#include "/home/user/sample/X_Module/X_Module_Module.h"
}
int main()
{
printStatus();
return 0;
}
now, firstly i compiled the c code which is located at X_Module folder
user@user-desktop:~/sample$ ls
user@user-desktop:~/sample/X_Module$ ls
X_Module.c X_Module.h X_Module.o Makefile
user@user-desktop:~/sample/X_Module$
then i compiled the sample folder.
X_Module main.o
main.cpp Makefile
user@user-desktop:~/sample$
Here is the Makefiles:
This is the X_Module's Makefile:
SRCS = X_Module.c
OBJS = $(SRCS:.c=.o)
CCOPTS = -Wall -g -O2
.c.o : $(CCOPTS)
$(CC) -c $<
all: $(OBJS)
clean:
rm -f *.o *~
This is the main's Makefile:
SYSDEF = TGS
LIBDIR = /usr/lib
CXXFLAGS = -Wall -g -O2 \
-DCMP_KUS \
-DCMP_RFM1G -DDEBUG
CFLAGS = -g -O2 \
-DCMP_RFM2G -DDEBUG -DLINUX -DCMP_$(SYSDEF)
LFLAGS = -lpthread -lexpat -lxerces-c -lvmic -L$(LIBDIR)/rfm2g -lrfm2g
CXXSRCS = main.cpp
CSRCS = /home/user/sample/X_Module/X_Module.c
CXXOBJS = $(CXXSRCS:.cpp=.o)
COBS = $(CSRCS:.c=.o)
all: sample
sample: ${COBJS} ${CXXOBJS}
${CXX} ${COBJS} ${CXXOBJS} -o sample ${LFLAGS}
clean:
rm -f sample ${COBJS} ${CXXOBJS}
dep:
${CXX} ${CXXFLAGS} -MM ${CXXSRCS} > .depends
${CC} ${CFLAGS} -MM ${CSRCS} >> .depends
include .depends
when i try to compile main, i'm getting this error:
user@user-desktop:~/sample$ touch .depends
user@user-desktop:~/sample$ make dep
g++ -Wall -g -O2 -DCMP_KUS -DCMP_RFM1G -DDEBUG -MM main.cpp > .depends
cc -g -O2 -DCMP_RFM2G -DDEBUG -DLINUX -DCMP_TGS -MM /home/user/sample/X_Module/X_Module.c >> .depends
user@user-desktop:~/sample$ make all
g++ -Wall -g -O2 -DCMP_KUS -DCMP_RFM1G -DDEBUG -c -o main.o main.cpp
g++ main.o -o sample -lpthread -lexpat -lxerces-c -lvmic -L/usr/lib/rfm2g -lrfm2g
main.o: In function `main':
/home/user/sample/main.cpp:22: undefined reference to `printStatus'
collect2: ld returned 1 exit status
make: *** [sample] Error 1
user@user-desktop:~/sample$
Do you have any idea why i'm getting this error?
Oct 21, 2009 at 12:15pm UTC
I do not see you linking against X_Module.o which contains the implementation of printStatus.