Compiling pure C and C ++

Can I compile the following 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
+3
source share
1 answer

No, not as it is written. Binding will not be able to find a function func()that, as a rule, will be crippled, which will be your hint.

You need to tell the C ++ compiler that the file file.hdeclares a C function using:

extern "C" {
#include "file.h"
}

This is because C ++ does name management that is not used in C. See this Wikipedia article .

As minor points:

  • Function C should be const char * func(void);. Empty parentheses do not mean the same thing in C as in C ++.
  • ++ cout <<, printf().
  • printf(), , . , "" - , printf("%s\n", func()); .
+14

All Articles