Visual Studio Pre build events and batch set

2019-07-29 12:24发布

问题:

I'm trying to create call a batch file which sets a bunch of environment variables prior to building.

The batch file looks something like this (it's automatically generated before-hand to detect ATI Stream SDK or NVidia CUDA toolkit):

set OCL_LIBS_X86="%ATISTREAMSDKROOT%libs\x86"
set OCL_LIBS_X64="%ATISTREAMSDKROOT%libs\x86_64"
set OCL_INCLUDE="%ATISTREAMSDKROOT%include"

However, the rest of the build doesn't seem to have access to these variables, so when I try to reference $(OCL_INCLUDE) in the C/C++>General>Additional include directories, it will first give me warning that environment variable $(OCL_INCLUDE) was not found, and when I try to include CL/cl.hpp the compile will fail with:

fatal error C1083: Cannot open include file: 'CL/cl.hpp': No such file or directory

I know that I could put these variables into the registry if I wanted to access them from the visual studio GUI, but I would really prefer not to do this. Is there a way to to get these environment variables to stick after the pre-build events? I can't reference $(ATISTREAMSDKROOT) directly because the project must be able to build for both ATI Stream and NVidia Cuda.

回答1:

a pre-build event is executed in it's own shell (VS spawns a cmd.exe process), hence all your calls to set are local to that instance only. Since you say your batchfile is pre-generated, there's no real need to use a pre-build event, is there? Because there are other ways to get VS to get access to these variables:

Instead of simply launching VS, launch a shell, call the batchfile, then launch devenv.exe. Or make a batch file to do all of this:

set OCL_LIBS_X86="%ATISTREAMSDKROOT%libs\x86"
set OCL_LIBS_X64="%ATISTREAMSDKROOT%libs\x86_64"
set OCL_INCLUDE="%ATISTREAMSDKROOT%include"
%comspec% /k "%VCINSTALLDIR%\vcvarsall.bat" x86
devenv.exe

Another option: instead of generating a batch file, generate a property sheet containing the variables and have your project(s) include the property sheet. This way you don't resort to environment variables, it's more 'the VS way' to work with variables. Add the file by setting 'Inherited Project Properties' in the general project setting, or adding 'InheritedPropertySheets=my.vsprops' to the Configuration section in your vcproj file. Example property sheet file:

<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioPropertySheet
ProjectType="Visual C++"
Version="9.00"
Name="toolkit_selector"
>
<UserMacro
    Name="OCL_LIBS_X86"
    Value="$(ATISTREAMSDKROOT)libs\x86"
/>
<UserMacro
    Name="OCL_INCLUDE"
    Value="$(ATISTREAMSDKROOT)include"
/>
</VisualStudioPropertySheet>