Home > Back-end >  Can I use symbols defined in a .c file in a .cpp file?
Can I use symbols defined in a .c file in a .cpp file?

Time:01-14

I prefer coding in C but I'm using DirectX which is a massive pain to use without C so all my files are .c except the ones that deal with DirectX. However whenever I try to link a C file with external symbols that are in a C file or vice versa I get unresolved external symbol linker error. Is it possible to link a project that uses .cpp and .c and have the symbols be recognized?

CodePudding user response:

Can I use symbols defined in a .c file in a .cpp file?

Yes, you can, with the requirement that the names mustn't be reserved in C (such as keywords that don't exist in C etc.).

In order to use the C names in C , they must be declared with C language linkage using a extern "C" declaration.

CodePudding user response:

I am assuming you are using a Microsoft environment like Visual Studio. If you open up the project properties, under Advanced, one of the options is Compile As. There are 3 options

  1. Default - .c compiles as C, .cpp compiles as C
  2. /TC - both .c and .cpp compile as C
  3. /TP - both .c and .cpp compile as C

If you wish to use extern "C", which is the option that most people go for, just leave it as default. If you do not wish to use extern "C", then try option 3 - compile everything as C .

Option 3 assumes you are no using c99 specifics like dynamic array allocation on the stack.

  •  Tags:  
  • Related