Makefile with mixed c and C++ code

2019-09-11 07:55发布

问题:

I'm trying to do something pretty simple in compiling .c and .cpp files to create an application on Ubuntu. I created a Makefile but it fails with the following error.

~/code/test$ make
gcc -Wall -c test1.c -o test1.o
g++ -c -Wall -D__STDC_LIMIT_MACROS main.cpp -o main.o
g++ -c -Wall -D__STDC_LIMIT_MACROS class_a.cpp -o class_a.o
echo g++ test1.o                               main.o class_a.o  -o myapp
g++ test1.o main.o class_a.o -o myapp
g++ test1.o                               main.o class_a.o -o myapp
main.o: In function `main':
main.cpp:(.text+0x21): undefined reference to `add(int, int)'
collect2: error: ld returned 1 exit status
make: *** [myapp] Error 1

main.cpp is as follows

#include "stdio.h"
#include "test1.h"
#include "class_a.h"

int main(int argc , char **argv)
{
   int c = 0; 
   c  = add(10, 15);
   A a;
   a.addToA(c);
   printf("result = %d\n",c); 
}

test1.h

#ifndef _FILE_H
#define _FILE_H

int add(int a, int b);
#endif 

test1.c

#include "test1.h"


int add(int a, int b)
{
    return a + b;
}

class_a.h

#ifndef _class_A_H
#define _class_A_H
class A 
{
public:
    A();

    int addToA(int c);

private:
    int a;

}; 

#endif // _class_A_H

class_a.cpp

#include "class_a.h"

A::A()
{
    a = 0;
}


int 
A::addToA(int c)
{
    a += c;
    return a;
}

Makefile

CXX = g++
CC = gcc
CFLAGS = -Wall -c
CXXFLAGS = -c -Wall -D__STDC_LIMIT_MACROS


CSOURCES=test1.c   

CPPSOURCES= main.cpp \
            class_a.cpp 


COBJECTS=$(CSOURCES:.c=.o)                              
CPPOBJECTS = $(CPPSOURCES:.cpp=.o) 
EXECUTABLE=myapp



all: $(EXECUTABLE)

$(EXECUTABLE): $(COBJECTS) $(CPPOBJECTS)
    echo $(CXX) $(COBJECTS) $(CPPOBJECTS) -o $@
    $(CXX) $(COBJECTS) $(CPPOBJECTS)-o $@


.c.o:
    $(CC) $(CFLAGS) $< -o $@

.cpp.o:
    $(CXX) $(CXXFLAGS) $< -o $@

clean:
        rm -rf $(COBJECTS)
        rm -rf $(CPPOBJECTS)
        rm -rf $(EXECUTABLE)

回答1:

To be able to call C functions from C++ (or C++ functions from C) you have to prevent the C++ name mangling, so that the linker will work properly.

That is, C function int add(int, int) actually generates a symbol in the object file called add. But a C++ function int add(int, int) will generate a symbol named _Z3addii. And those will not link.

Solution: the mixed language functions, when compiled in with C++ should be declared extern "C". Unfortunately the extern "C" declaration does not exist in C, only in C++.

So the standard idiom is:

test1.h

#ifndef _FILE_H
#define _FILE_H

#ifdef __cplusplus
extern "C" {
#endif

int add(int a, int b);

#ifdef __cplusplus
}  //extern "C"
#endif

#endif

That way, the C code is just as before, but the C++ code will look for the add function using the undecoraded name, and all will link together.