0

Would there be any difference between both notations when compiling in a .c file or within a .cpp file ?

JkT
  • 103
  • 7
  • Does this answer your question? [Windows & C++: extern & \_\_declspec(dllimport)](https://stackoverflow.com/questions/2288293/windows-c-extern-declspecdllimport) – Sercan Jan 19 '22 at 19:17
  • 3
    Wasn't part of the point in this https://stackoverflow.com/questions/70768093/error-c2220-warning-treated-as-error-no-object-file-generated question of yours, that the former doesn't compile? – PMF Jan 19 '22 at 19:17
  • There's no `extern "C"` in C (only in C++) (and even if it would exist it would do nothing) - so this question only applies to C++. – Turtlefight Jan 19 '22 at 19:44
  • @PMF exactly it doesn't link. I get a unresolved external linking error when extern term appears before the __declspec(dllimport). What I was looking for was an explanation of using extern before and after the__declspec(dllimport) and the effect it has on name mangling. – JkT Jan 19 '22 at 19:58
  • **I get a unresolved external linking error when extern term appears before the __declspec(dllimport)** Could you provide a minimal, reproducible example? – Minxin Yu - MSFT Jan 20 '22 at 08:11

1 Answers1

4

extern "C" and __declspec(dllimport) are totally orthogonal.

  • extern "C" means that C linkage should be used for that symbol. I.e. no C++ name mangling will be applied. It also limits functions' interfaces to C-compatible things: built-in types, trivial structs, and pointers. Essentially, it tells the compiler and linker that a symbol should be found in the "C way" rather than the "C++ way". extern "C" is generally used for either calling C functions from C++ code or creating a C-compatible interface to C++ code.
  • __declspec(dllimport) tells the linker that a symbol will be loaded dynamically at runtime from a DLL.

The two can be combined as well. A function marked extern "C" __declspec(dllimport) will be dynamically linked and use C-style linkage.

Miles Budnek
  • 28,216
  • 2
  • 35
  • 52
  • 1
    I remember that Petzold's old Programming Windows bible placed all of it in a single macro or typedef, conditionally, depending on if compiled as C or C++, which is probably still a good idea, to hide all of that away. – Lundin Jan 19 '22 at 19:50