Compiling pure C and C++
c, c++
Solution
No, not as written. The linking will fail to find the `func()` function, which will typically be "mangled" which will be your clue.
You need to tell the C++ compiler that the `file.h` file declares a C function, by using:
extern "C" {
#include "file.h"
}
This is because C++ does name-mangling which isn't used in C. See this Wikipedia article.
As minor points:
- The C function should be `const char * func(void);`. Empty parenthesis don't mean the same thing in C as in C++.
- The C++ should use `cout <<`, not `printf()`.
- Even if using `printf()`, don't use externally-sourced text as the first argument, it can be dangerous. Less so when the "external" is still your own source file of course, but it's better to write `printf("%s\n", func());` and be safe.
Problem
Can i compile next code ? main.CPP c++ languge file ``` #include <stdio.h> #include "file.h" int main() { printf("Hello"); printf(func()); return 0; } ``` file.C c languge file ``` #include "file.h" char* func() { return "This is a C string"; } ``` file.H ``` #ifndef FILE_H #define FILE_H char* func(); #endif // FILE_H ```