3
votes

Why C++/CLI compiler can compile this code:

using namespace System;

inline void Assembly(){

__asm{
mov eax,5
}

}

int main(array<System::String ^> ^args)
{

    Assembly();
    Console::WriteLine(L"Hello World");
    return 0;
}

And can NOT for this one:

using namespace System;


int main(array<System::String ^> ^args)
{

__asm{
mov eax,5
}
    Console::WriteLine(L"Hello World");
    return 0;
}
1
Do you get an error message? Does it talk about reachability? - Brian Cain
@BrianCain: it gave 5 errors for the second code, one of them is Error 1 error C3644: 'main' : cannot compile the function to generate managed code. - Aan

1 Answers

13
votes

The C++/CLI compiler supports generating both machine code and IL. It will generate machine code for any code that is compiled without /clr in effect or functions that are bracketed with #pragma managed(push, off) and #pragma managed(pop). Or functions that must be compiled to machine code because they contain code that cannot be translated to IL. Like _asm, note the C4793 warning you got for the first snippet. Suppress the warning with #pragma managed. Such code cannot use any managed types of course.

The unit of code generation is a function. What cannot work is a function that needs both. Your main() function must be compiled to IL because it uses managed types. The function won't be inlined of course.