Hello, I'm a a pretty new programmer just beginning to play around with C and C++. I use Linux and am compiling with gcc/g++ 4.3.2 however I'm coming across a strange problem that I just can't resolve. I'm trying to write a simple program to just see the possibilities of calling C++ code from C. The main() function is in C : #include <stdio.h> #include <stdlib.h> #include "cpp_main.h" /* * */ int main(int argc, char** argv) { int return_value; return_value = cpp_main(argc,argv); return (return_value); } Code (markup): The function cpp_main() is written in C++, and is in file cpp_main.cpp : #include "cpp_main.h" //#include "testclass.h" //int cpp_main(int argc, char** argv); /*extern "C" { int cpp_main(int argc, char** argv); }*/ int cpp_main(int argc, char** argv){ char *testtext = "Some Test Text to display.\n"; //TestClass::WriteMessage(testtext); return(0); } Code (markup): And cpp_main.h is : //#ifndef _CPP_MAIN_H //#define _CPP_MAIN_H // Declare cpp_main() function //int cpp_main(int argc, char** argv); extern "C" { void cpp_main(int argc, char** argv); }; //#endif /* _CPP_MAIN_H */ Code (markup): However when I try to build the executable I receive this error : cpp_main.h:6: error: expected identifier or ‘(’ before string constant gcc is telling me there is something wrong with extern "C"... ?!?!!? If I take the line from the header file and paste it directly into cpp_main.cpp everything compiles and links ok... but why won't it work with the header file ? Any help is much appreciated Steve
Yes.. I see the error of my ways now. So the obvious thing (which I did) was to remove the #include "cpp_main.h" from the C file, but I expected this then to cause an 'un-declared' function error or error that the function cpp_main() could not be found but no.. gcc compiled and linked with no complaints at all... so what's the point of a header file if it's not needed to link or declare functions.. or have I misunderstood the purpose of headers ?
Usualy if you need declare function written in C you have to use something like this #ifdef __cplusplus #define EXTCFUNC extern "C" #elseif #define EXTCFUNC extern #endif EXTCFUNC cpp_main(int argc, char** argv); Code (markup):