How to set search path of a process created from CreateProcess
-
14-12-2019 - |
Question
I am using CreateProcess
to invoke cl
to compile and link another C++ program (TestProg.cxx
) into a DLL. I invoke cl.exe
with the following compilation options:
compilation options:
/Od /nologo /Fo /RTC /w /Zc TestProg.cxx /DLL
the call:
if ( CreateProcess(PATH_TO_EXE, COMPILATION_OPTIONS, NULL,NULL,
FALSE,0,NULL,NULL,&si,&pi) )
{
//....
}
If TestProg.exe
contains #include <iostream.h>
I got the following compilation error:
TestProg.cpp(1) : fatal error C1034: iostream.h: no include path set
Without any #include
command, I got the following linkage error:
LINK : fatal error LNK1104: cannot open file 'LIBCMT.lib'
What am I doing wrong?
I searched the answer for the last 6-7 hours on the web, but didn't find it. Using windows API is new to me.
Solution
If you look at the definition of CreateProcess
:
BOOL WINAPI CreateProcess(
__in_opt LPCTSTR lpApplicationName,
__inout_opt LPTSTR lpCommandLine,
__in_opt LPSECURITY_ATTRIBUTES lpProcessAttributes,
__in_opt LPSECURITY_ATTRIBUTES lpThreadAttributes,
__in BOOL bInheritHandles,
__in DWORD dwCreationFlags,
__in_opt LPVOID lpEnvironment,
__in_opt LPCTSTR lpCurrentDirectory,
__in LPSTARTUPINFO lpStartupInfo,
__out LPPROCESS_INFORMATION lpProcessInformation
);
You're setting the optional parameter __in_opt LPVOID lpEnvironment,
to NULL
.
According to said definition:
A pointer to the environment block for the new process. If this parameter is NULL, the new process uses the environment of the calling process.
cl.exe
gets its include location information and library search paths from environment variables - have a look at setenv.bat
in the VS directory. In this case, neither your calling process or your target process are running in an environment where these variables are set.
You have a choice - you can create the environment variables yourself according to the MSDN:
An environment block consists of a null-terminated block of null-terminated strings. Each string is in the following form:
name=value\0
Because the equal sign is used as a separator, it must not be used in the name of an environment variable.
Or you can require your program to be run from the VS tools prompt. A good check this is actually the problem would be to run your program from this prompt, rather than Visual Studio, to see if that fixes the issue.
The reason not using #include
produces a linker error is due to the fact if there are no includes, cl.exe
won't look for them - it then looks for the C/C++ runtime libs.
As a side note - I believe the standard in C++ is to #include <iostream>
i.e without the .h
.