I am working on a project in which some people have already written C ++ code, and we should use it in our C code. Therefore, I tried the following test to write a test program that demonstrates the same thing:
Header file:
#ifndef h_files_n #define h_files_n #include<iostream> #ifdef __cplusplus extern "C" { #endif void add_func(int, int); #ifdef __cplusplus } #endif #endif
Cpp file:
#include"h_files.h" void add_func(int num, int nums) { std :: cout << "The addition of numbers is : "<< num+nums << std endl; }
File c:
#include<stdio.h> #include"h_files.h" int main() { printf("We are calling the C function form C++ file.\n"); add_func(10,15); return 0; }
makefile:
CC = gcc inc = -I include vpath %.c src vpath %.cpp src vpath %.o obj all : $(addprefix obj/,functions.o main.o) run run : main.o functions.o $(CC) -o bin/ $@ $^ obj/%.o : %.cpp $(CXX) -c $(inc) $^ -o $@ -libstdc++ obj/%.o : %.c $(CC) -c $(inc) $^ -o $@ .PHONY : clean clean : -rm -f obj/* bin/*
I get the following error:
g++ -c -I include src/functions.cpp -o obj/functions.o gcc -c -I include src/main.c -o obj/main.o gcc -o bin/run obj/main.o obj/functions.o obj/functions.o: In function `add_func': functions.cpp:(.text+0x1e): undefined reference to `std::cout' functions.cpp:(.text+0x23): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::operator<< <std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&, char const*)' functions.cpp:(.text+0x2d): undefined reference to `std::ostream::operator<<(int)' functions.cpp:(.text+0x32): undefined reference to `std::basic_ostream<char, std::char_traits<char> >& std::endl<char, std::char_traits<char> >(std::basic_ostream<char, std::char_traits<char> >&)' functions.cpp:(.text+0x3a): undefined reference to `std::ostream::operator<<(std::ostream& (*)(std::ostream&))' obj/functions.o: In function `__static_initialization_and_destruction_0(int, int)': functions.cpp:(.text+0x68): undefined reference to `std::ios_base::Init::Init()' functions.cpp:(.text+0x77): undefined reference to `std::ios_base::Init::~Init()' collect2: error: ld returned 1 exit status make: *** [run] Error 1
- If I use g ++ as a linker, then it works fine. But the gcc linker gives me a problem.
- I think the problem is with changing the name of the g ++ function, and gcc does not control function names (characters).
- So, is there any compiler flag that, if possible, would have avoided a name change.
- The reason for avoiding the g ++ linker is because it treats the link as a C ++ style, but the underlying code is in C, so an error may occur when calling the code.
Please someone suggest a solution.
source share