问题描述:

I know the code below used to be C, however, I wrote it in visual studio 2008 as a c++ program and it works fine (it is saved as C++). However, the program is in C code, correct? (or is it?).

So, when I tried to compile it inside Visual Studio as C (Go to-> Properties of file -> c/c++ ->Advanced -> Compile as -> changed it to 'Compile as C code') I then get many errors, the main of which it does not recognize the LPSTR type. So, I guess my question is: is it C or C++ code and if it is C, why did it not work when I changed it to compile C code?

#include "stdafx.h"

#include <stdio.h>

#include <windows.h>

#include <strsafe.h>

#include <direct.h>

#include <string.h>

#include <conio.h>

int main(VOID)

{

STARTUPINFO si;

PROCESS_INFORMATION pi;

//allocate memory

ZeroMemory(&si, sizeof(si));

si.cb = sizeof(si);

ZeroMemory(&pi, sizeof(pi));

//create child process

if (!CreateProcess(NULL,

L"C:\\Windows\\Notepad.exe",

NULL,

NULL,

FALSE,

0,

NULL,

NULL,

&si,

&pi))

{

fprintf(stderr, "create process failed");

return -1;

}

//parent waits for child to complete

WaitForSingleObject(pi.hProcess, INFINITE);

printf("Child Complete");

//close handle

CloseHandle(pi.hProcess);

CloseHandle(pi.hthread);

}

网友答案:

It compiles cleanly as C. The only error is triggered by CloseHandle(pi.hthread), since it's not a member of PROCESS_INFORMATION. You're looking for hThread (capital T).

网友答案:

It's C. But most C++ compilers are capable compiling C code. The header conio.h is not a part of standard C so you may want to avoid that.

LPSTR is defined in windows.h and since you have included it, it shouldn't give any error. It is typedef'ed:

typedef char* PSTR, *LPSTR; 

For other typedef'ed variables in your code, you have to check if their headers. Try including Winbase.h

网友答案:

From what you give we can't see if it is valid C because you are using non-standard headers and macros. But I can imagine that there could be macro definitions that turns this into C code.

If it is C, it is not so good one, and not so good one for C++ either. Both languages have their way of initializing variables, but your code uses none of them. In particular in C (and for PODs in C++) there are initializers for initializing variables. Supposing that both ugly macros here expand to types:

STARTUPINFO si = { 0 };
PROCESS_INFORMATION pi = { 0 };

of if you have a C99 compliant compiler the first would even better be

STARTUPINFO si = { .cb = sizeof si };

If for some reason you'd need a function to zero out a whole block of memory, better use the standard function memset for that. But if you use the correct initializers in C (or constructors in C++) you should rarely need that explicitly.

网友答案:

every c code is a valid c++ code. but its not the other way around. So if you want to use OS api's which are c++ then you should compile it as c++.

相关阅读:
Top