I\'ve read related questions like this and this, and other pages, but they don\'t really answer my question.
Basically, I see code like the following.
I've learnt from here and here that macros like that above are used to tell the linker how to link it properly, or something like that.
To be pedantic, it's not the macro that tells the linker how to link. The macro is simply replaced by the preprocessor by whatever text it's defined to be replaced with. In the case of your example, it would be conditionally replaced with __declspec(dllexport)
or __declspec(dllimport)
. Those declspec specifiers on the other hand do tell the linker what to do... at least some linker that understands the specifier.
since when was it legal to just put something like __declspec(dllimport) in the middle of a class declaration anyway?
Since Microsoft implemented their compiler and specified that it's legal. It's not legal according to the c++ standard.
In which part of the C++ standard does it say that class declarations like this are legal?
It doesn't. Using those specifiers is non-standard and not guaranteed to work in any other compiler than Microsoft's. That's why such macro is typically defined to expand to an empty string (or possibly something else, specific to another implementation) when used in a compiler that does not support the keyword.
What actual thing is __declspec(dllimport)?
It is a non-standard keyword. You can find out more from their (Microsoft) documentation.
To dive a little bit deeper, the keywords tell the linker how to export symbols when compiling a shared (dynamically linked) library. Dynamic linking is a concept that's entirely foreign to the standard. It's implementation defined.
how I might go about using this kind of declaration myself, in a program that I might write from scratch, myself.
Do you intend to write a shared library? If not, then you don't need to know. If yes, then you need to read the documentation of every platform that you're targetting.
Here is a walkthrough in the Microsoft's documentation that guides you through the steps to create a dynamically linked library.