I am new to C++ coding, coming from Java and C# background. I'm puzzled by the proliferation of #define terms starting with the most basic:
#define _tmain wmain
When I first learned a smattering of C ages ago, the main function was:
int main(int argc, char *argv[])
In the Visual C++ project I created, it made the main function:
int _tmain(int argc, _TCHAR* argv[])
I'm just wondering why there needed to be a name translation from wmain
to _tmain
? Why not just use the original C main
function prototype?
In general there seems to be lot of #define renaming something which looks pretty clear to start with, to something which looks more mysterious and less clear (I mean wmain
to _tmain
??).
Thanks for tolerating what may be a very obvious question.
A macro is a piece of code in a program that is replaced by the value of the macro. Macro is defined by #define directive. Whenever a macro name is encountered by the compiler, it replaces the name with the definition of the macro. Macro definitions need not be terminated by a semi-colon(;).
which keyword is used to define the macros in c++? Explanation: #define is the keyword which is used to define the macros in c++.
_tmain is a Microsoft extension. main is, according to the C++ standard, the program's entry point.
This is a Visual C++-specific feature, it's not a part of C++.
Most of the Windows API functions have two versions: those that end in W
, which are for use with wide character strings (wchar_t
strings) and those that end in A
, which are for use with narrow character strings (char
strings). The actual Windows API "functions" don't have any suffix and are defined as macros that expand to the right version depending on the settings.
The T
names (like _TCHAR
and _tmain
) are for the same purpose: they are macros that expand to the right name depending on your compilation settings, so wchar_t
and wmain
for wide character support, or char
and main
for narrow character support.
The idea is that if you write your code using the character-type-agnostic names (the T
names), you can compile your code to use narrow characters (ASCII) or wide characters (Unicode) without changing it. The tradeoff is that your code is less portable.
Because Microsoft decided that the best way to add Unicode support to C++ was to add a TCHAR
type, which is #defined to either char
or wchar_t
depending on the value of Project Properties > Configuration Properties > General > Character Set. _tmain
is also #defined to either main
(which takes char
s) or wmain
(which takes wchar_t
s) depending on that setting.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With