简体   繁体   中英

Visual Studio does not differentiate between C headers and C++ headers

I am work with C language with Visual Studio 2017-enterprise but there is a complex problem with C header files because Visual Studio considers every header is a C++ header. So, whether the extension is .hpp or .h , it will treat it as a C++ header, and this causes problem because I used C99 and Visual Studio will consider the header is C++ so I can't use C features in the header file.

Note : When I name a source file to .c , Visual Studio treats it as a C file, not C++, and it's good. So I need to do the same with headers. I need to make .h for c and .hpp for c++ How?

This problem also with VS 2010, 2013, 2015.

EDIT::

the problem with highlighting for example if i create class in .c file visula studio will say there is error but this will not show any error if i create class in .h file even if i use extern"C"

look At This image : source.h Now Look At This source.c

If you #include a .h file from a .c file then Visual Studio will compile it as C. If you #include a .h file from a .cpp file then Visual Studio will compile it as C++.

It's common to do this in C-specific headers:

#ifdef __cplusplus 
extern "C" {
#endif

void MyCFunction();
void MyCFunction2();

#ifdef __cplusplus 
}
#endif

This allows you to declare functions which are implemented in C. Other C-sources can use these functions, and C++ sources can use these functions.

You don't really need to worry about C++-specific headers because you'll just get compilation errors if you #include them in a C source.

The problem you're having as I understand it is that you are trying to develop C code in vscode, however the editor keeps trying to treat *.h files as C++ files and not C files, fundamentally this is because as far as I can tell MS hates C . I had the same problem, so here is the solution I ended up using:

  1. Open the command palette by pressing Ctrl + Shift + P
  2. Start typing Preferences: Configure language specific settings
  3. Choose C , this will open Settings.json
  4. If the key "files.associations" isn't defined, you'll have to define it, and add the "*.h": "c", property in it.

At the end the file should look like this:

{
    //...other settings

    "files.associations": {
        "*.h": "c",
    },

    //...other settings
}

This will set the editor mode to C whenever you open a file ending with a .h . You can define similar settings for all these languages .

"This causes problem because I used C99 and Visual Studio will consider the header is C++ so I can't use C features in the header file."

No, the problem is that Visual Studio does not support C99 anywhere, neither in header files nor in .C files. Visual Studio follows ISO C90.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM