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 :
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 ?
Also, extern "C" is only defined in C++ compiliers, so if you are compiling with a C compilier, you can't compile it. Put #ifdef _cplusplus (I think) around it with correct #endif s.
OK, well as in my original post, can you explain why this compiles :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//#include "cpp_main.h"
//#include "testclass.h"
//=========================================
// Include the header in cpp_main.cpp
//=========================================
//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);
}
Yet if I separate decelerations into a header file, this does NOT compile, giving the error I originally stated :
cpp_main.h
1 2 3 4 5 6
// Declare cpp_main() function
//int cpp_main(int argc, char** argv);
extern"C" {
int cpp_main(int argc, char** argv);
};
cpp_main.cpp
1 2 3 4 5 6 7 8 9
#include "cpp_main.h"
int cpp_main(int argc, char** argv){
char *testtext = "Some Test Text to display.\n";
//TestClass::WriteMessage(testtext);
return(0);
}
I'm using gcc and it has the capability to determine the source type (C or C++) from the file extension and passes it to the appropriate compiler in the toolchain, therefore I do not believe it's a problem due to trying to compile C++ with a C compiler.
melkiy:
I was playing round with the return type and forgot to put it back before quoting the code here in the forum. Also it's not because I didn't have a semi-colon after the 'extern' decleration.
I managed to solve the problem - I had included a C++ header in the C file which contains main() (as you'll see from my original post)
I had a misunderstanding of the use of headers - I thought they were there to enable the linker to resolve references to functions in other files. I was therefore skeptical at first removing the C++ #include expecting an 'unresolved function' error - but no gcc doesn't necessarily use headers to resolve
Thanks for your help though.. tis much appreciated by a newbie !