How do I start a new CUDA project in Visual Studio 2008? - c++

This is an incredibly basic question, but how do I start a new CUDA project in Visual Studio 2008? I have found tons and tons of documentation about CUDA related matters, but nothing about how to start a new project. I am working with Windows 7 x64 Visual Studio 2008 C++. I would really like to find some sort of really really basic Hello World app to just get a basic program compiling and running.
Edit:
I tried your steps Tom. I setup a console app. I then deleted the default .cpp it drops in and copied over the three files from the template project just to have something to compile. When I compile that, template_gold.cpp complained about not having stdafx.h included, so i included that. Now the build fails with this:
1>------ Build started: Project: CUDASandbox, Configuration: Debug x64 ------
1>Compiling...
1>template_gold.cpp
1>Linking...
1>LIBCMT.lib(crt0.obj) : error LNK2019: unresolved external symbol main referenced in function __tmainCRTStartup
1>D:\Stuff\Programming\Visual Studio 2008\Projects\CUDASandbox\x64\Debug\CUDASandbox.exe : fatal error LNK1120: 1 unresolved externals
1>Build log was saved at "file://d:\Stuff\Programming\Visual Studio 2008\Projects\CUDASandbox\CUDASandbox\x64\Debug\BuildLog.htm"
1>CUDASandbox - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

NOTE With the release of version 3.2 of the CUDA Toolkit, NVIDIA now includes the rules file with the Toolkit as opposed to the SDK. Therefore I've split this answer into two halves, use the correct instructions for your version of the Toolkit.
NOTE These instructions are valid for Visual Studio 2005 and 2008. For Visual Studio 2010 see this answer.
CUDA TOOLKIT 3.2 and later
I recommend using the NvCudaRuntimeApi.rules file (or NvCudaDriverApi.rules if using the driver API) provided by NVIDIA, this is released with the toolkit and supports the latest compiler flags in a friendly manner. Personally I would advise against using the VS wizard, but only because I really don't think you need it.
The rules file (installed into the Program Files\Microsoft Visual Studio 9.0\VC\VCProjectDefaults directory) "teaches" Visual Studio how to compile and link any .cu files in your project into your application.
Create a new project using the standard MS wizards (e.g. an empty console project)
Implement your host (serial) code in .c or .cpp files
Implement your wrappers and kernels in .cu files
Add the NvCudaRuntimeApi.rules (right click on the project, Custom Build Rules, tick the relevant box), see note 1
Add the CUDA runtime library (right click on the project and choose Properties, then in Linker -> General add $(CUDA_PATH)\lib\$(PlatformName) to the Additional Library Directories and in Linker -> Input add cudart.lib to the Additional Dependencies), see notes [2] and [3]
Optionally add the CUDA include files to the search path, required if you include any CUDA files in your .cpp files (as opposed to .cu files) (right click on the project and choose Properties, then in C/C++ -> General add $(CUDA_PATH)\include to the Additional Include Directories), see note [3]
Then just build your project and the .cu files will be compiled to .obj and added to the link automatically
Some other tips:
Change the code generation to use statically loaded C runtime to match the CUDA runtime; right click on the project and choose Properties, then in C/C++ -> Code Generation change the Runtime Library to /MT (or /MTd for debug, in which case you will need to mirror this in Runtime API -> Host -> Runtime Library), see note [4]
Enable syntax highlighting using the usertype.dat file included with the SDK, see the readme.txt in <sdk_install_dir>\C\doc\syntax_highlighting\visual_studio_8
I'd also recommend enabling Intellisense support with the following registry entry (replace 9.0 with 8.0 for VS2005 instead of VS2008):
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]
"NCB Default C/C++ Extensions"=".cpp;.cxx;.c;.cc;.h;.hh;.hxx;.hpp;.inl;.tlh;.tli;.cu;.cuh;.cl"
Incidentally I would advocate avoiding cutil if possible, instead roll your own checking. Cutil is not supported by NVIDIA, it's just used to try to keep the examples in the SDK focussed on the actual program and algorithm design and avoid repeating the same things in every example (e.g. command line parsing). If you write your own then you will have much better control and will know what is happening. For example, the cutilSafeCall wrapper calls exit() if the function fails - a real application (as opposed to a sample) should probably handle the failure more elegantly!
CUDA TOOLKIT 3.1 and earlier
I would use the Cuda.rules file provided by NVIDIA with the SDK, this is released alongside the toolkit and supports the latest compiler flags in a friendly manner. Personally I would advise against using the VS wizard, but only because I really don't think you need it.
The rules file (in the C\common directory of the SDK) "teaches" Visual Studio how to compile and link any .cu files in your project into your application.
Create a new project using the standard MS wizards (e.g. an empty console project)
Implement your host (serial) code in .c or .cpp files
Implement your wrappers and kernels in .cu files
Add the Cuda.rules (right click on the project, Custom Build Rules, browse for the rules file and ensure it is ticked)
Add the CUDA runtime library (right click on the project and choose Properties, then in Linker -> General add $(CUDA_LIB_PATH) to the Additional Library Directories and in Linker -> Input add cudart.lib to the Additional Dependencies), see note [2] below
Optionally add the CUDA include files to the search path, required if you include any CUDA files in your .cpp files (as opposed to .cu files) (right click on the project and choose Properties, then in C/C++ -> General add $(CUDA_INC_PATH) to the Additional Include Directories)
Then just build your project and the .cu files will be compiled to .obj and added to the link automatically
Some other tips:
Change the code generation to use statically loaded C runtime to match the CUDA runtime, right click on the project and choose Properties, then in C/C++ -> Code Generation change the Runtime Library to /MT (or /MTd for debug, in which case you will need to mirror this in CUDA Build Rule -> Hybrid CUDA/C++ Options), see note [4]
Enable syntax highlighting using the usertype.dat file included with the SDK, see the readme.txt in <sdk_install_dir>\C\doc\syntax_highlighting\visual_studio_8
I'd also recommend enabling Intellisense support with the following registry entry (replace 9.0 with 8.0 for VS2005 instead of VS2008):
[HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\9.0\Languages\Language Services\C/C++]
"NCB Default C/C++ Extensions"=".cpp;.cxx;.c;.cc;.h;.hh;.hxx;.hpp;.inl;.tlh;.tli;.cu;.cuh;.cl"
Incidentally I would advocate avoiding cutil if possible, instead roll your own checking. Cutil is not supported by NVIDIA, it's just used to try to keep the examples in the SDK focussed on the actual program and algorithm design and avoid repeating the same things in every example (e.g. command line parsing). If you write your own then you will have much better control and will know what is happening. For example, the cutilSafeCall wrapper calls exit() if the function fails - a real application (as opposed to a sample) should probably handle the failure more elegantly!
NOTE
You can also use a Toolkit-version-specific rules fule e.g. NvCudaRuntimeApi.v3.2.rules. This means that instead of looking for the CUDA Toolkit in %CUDA_PATH% it will look in %CUDA_PATH_V3_2%, which in turn means that you can have multiple versions of the CUDA Toolkit installed on your system and different projects can target different versions. See also note [3].
The rules file cannot modify the C/C++ compilation and linker settings, since it is simply adding compilation settings for the CUDA code. Therefore you need to do this step manually. Remember to do it for all configurations!
If you want to stabilise on a specific CUDA Toolkit version then you should replace CUDA_PATH with CUDA_PATH_V3_2. See also note 1.
Having mismatched version of the C runtime can cause a variety of problems; in particular if you have any errors regarding LIBCMT (e.g. LNK4098: defaultlib 'LIBCMT' conflicts with use of other libs) or multiply defined symbols for standard library functions, then this should be your first suspect.

What a great question!! For all the CUDA documentation out there, this is something that I've always thought was an obvious omission... In fact, I'm really glad I found this post, because after using CUDA for quite a while, I still hadn't found an official, correct way to get VS to produce a CUDA program from scratch.
When I've needed to start a new CUDA program, I've always just copied and modified the "template" example from the SDK directory. This may not be exactly what you're looking for, because it doesn't start fresh, but it is a quick way to get a CUDA-capable project working in VS with all the correct project/file names...
Make a copy of the "template" example from the SDK, and rename the directory -- the only necessary contents in the directory are source code and VS .sln and .vcproj files
Rename both .sln and .vcproj files
Open the .sln file in a text editor, and rename the Project variable and .vcproj filename in the 3rd line of the file
Open the .vcproj file in a text editor, and rename the Name and RootNamespace variables in the first few lines of the file
Open the project with VS, and open the Property Pages (right click on the project name in the solution explorer pane, select "Properties")
Change the Output File name in the Property Pages (under Configuration Properties -> Linker -> General) ... Before I change the filename, I select "All Configurations" from the Configuration pull-down and "x64" from the Platform pull-down, since I'm on a 64-bit system
Change the Program Database File name in the Property Pages (under Configuration Properties -> Linker -> Debugging) ... Before I change the filename, I select "Debug" and "x64" in the pull-downs.

Install CUDA VS wizard. It will setup VS and add CUDA Project to the "new project" menu.
Make sure that you have x64 compiler installed (must be checked during VS install).
Check if you have x64 libs, includes, nvcc dir and in the search path.
Create new project using CUDA template.
Change project type to x64 and CUDA setting to Native (if you have nv cuda-enabled card) or emulation otherwise.
The template will create custom build rules that compile .cu files with nvcc and other files with default compiler.
if, vs is trying to compile .cu files with C/C++ compiler, click on that file in solution explorer and disable compilation for that files (red dot on file's icon)
Additional info about installing CUDA wizard on VS2008 can be found here and here
[edit]
If you don't want to use wizard you have to setup CUDA lib/include/nvcc paths manually and add custom build rules to each new CUDA program. For additional info how to do it take a look at Tom's Answer.

You may want to take a look at this guide: http://www.programmerfish.com/how-to-run-cuda-on-visual-studio-2008-vs08/

Related

In Visual Studio 2019, linking plain C++ project to Dot Net 5 project builds an invalid executable

Summary: I am using Visual Studio 2019, and trying to create an example that links a plain-old-C++ project to a C++/CLR project that targets .NET 5.0. The solution compiles and builds, but attempting to run it produces an error message saying "not a valid Win32 application."
Question: How can I produce an executable that will actually run?
Steps to reproduce:
Using Visual Studio 2019, create a new solution. Set the configuration to Debug and x86.
Create a new project that is a C++ desktop application, using the C++ Windows Desktop Wizard project template with default options. Name it Interop5Test, and verify that it builds and runs.
Create a new project that is a C++/CLR project targeting .NET 5.0, using the C++ CLR Class Library (.NET Core) template, and name it CppShim5.
Modify the properties and source files of CppShim5 to remove the use of precompiled headers. (I did so to match the requirements of my intended use case.) Verify that the solution still builds and runs.
In the project properties for Interop5Test:
modify Linker | Input | AdditionalDependencies by adding ../CppShim5/$(Configuration)/CppShim5.obj
modify Linker | General | AdditionalLibraryDirectories by adding
C:\Program Files\dotnet\packs\Microsoft.NETCore.App.Host.win-x86\5.0.3\runtimes\win-x86\native
(or wherever ijwhost.lib can be found on your machine).
Build the solution, which should succeed.
Press Local Windows Debugger in Visual Studio to start the executable, and observe a popup window that says "Unable to start program ... not a valid Win32 application."
Browse to the Debug folder of the solution, and observe that Interop5.exe, CppShim5.dll, ijwhost.dll, and CppShim5.runtimeconfig.json are all present.
Use ildasm to examine Interop5.exe and CppShim5.dll, and observe that they are 32-bit portable executables with COFF Header | Machine value of 0x14c which means "Intel 386 or later processors and compatible processors."
Open ijwhost.dll with Visual Studio and observe a reasonable looking Version resource. Perform a binary comparison of ijwhost.dll with the one in the additional library directory of step 5, and observe that the files match perfectly.
Examine the contents of CppShim5.runtimeconfig.json and see something that looks reasonable.
I discovered that I can get a valid executable if I link to CppShim5.lib instead of CppShim5.obj.
Details for how to alter the example in the original question:
Add a class to CppShim5 and mark it as exported from the DLL (by using __declspec(dllexport), see also: https://learn.microsoft.com/en-us/cpp/build/exporting-from-a-dll-using-declspec-dllexport?view=msvc-160). This causes Visual Studio to generate CppShim5.obj and to put it in the Solution's Debug folder.
Edit the properties of Interop5Test, changing Linker | Input | AdditionalDependencies from: ../CppShim5/$(Configuration)/CppShim5.obj to: ../$(Configuration)/CppShim5.lib
In Visual Studio, add to project Interop5Test a dependency on project CppShim5.
With these changes, build the solution. It should now execute.

How to include wx in my c++ code (MSVS 2019)

I want to include the wx library in my c++ program but following the given default instruction don't include the library in Visual Studio 2019
I tried (quoting from the instruction install.md):
Open a "Visual Studio Command Prompt"
Change directory to \%WXWIN\%\build\msw and type
> nmake /f makefile.vc
Also i tried to include the file wxwidgets.props as explained in the given instruction
If i try to do
#include <wx/frame.h>
is marked as mistake ("impossible to open "wx/frame.h" of origin file)
Note: for the creation of the GUI I'm also using wxFormBuilder
It's generally a good idea to read documentation when trying to use new software. In this case, the relevant documentation is in the file docs/msw/install.md (or install.txt in earlier wxWidgets versions) and its "Building Applications Using wxWidgets" section contains the information that you need.
After some time wondering around forum, I've found a video on Youtube explaining how to include wx in your Visual Studio project, so i decided to post the answer to my question helping how will need this help in the future like i needed.
First of all you need to open in the Wx Directory and go to wxWidgets-X.X.X\build\msw and open with Visual Studio wx_vc15.sln (or more recent if available)
Compiling the solution in Debug, DebugDLL, Relase and RelaseDLL.
Now open your project (new or old) and open the Project menu and tap Project propriety
Select configuration All configuration, go to section C/C++ and in Additional Include directorys add \wxWidgets-X.X.X\include
Next go under Preprocessor and add in Processor definition the string WXUSINGDLL
Go under Linker and on Additional library Directory add \wxWidgets-X.X.X\lib\vc_dll
Change configuration to debug and under C\C++ add another additional include directory that is wxWidgets-X.X.X\lib\vc_dll\mswud
Finally, as step 7, change to relase and add wxWidgets-X.X.X\lib\vc_dll\mswu
This will include the wx library in your code
Here the link for the video https://www.youtube.com/watch?v=EI2taYkErRg if you need more detail or if you need visually the explaination.
NOTE: in the install.md is missing the part of including the library in the project in this way, it mention only to compile the Debug version not well explaining why or what to do next.

Create MS Visual C++ DLL project out of existing sources

My goal is to compile existing C++ classes (legacy code, stored in a set of *.h files) into a DLL so that it can be further integrated into a C# application.
For that purpose, it seems best to use MS Visual Studio. I have no experience with this environment, so I tried the naive approach found on MSDN and other SO answers:
File | New | Project from existing code
selected Visual C++
selected file location that is base for include references used in those .h files
specified a project name
let the wizard find and add all C++ files below the directory
selected "Use Visual Studio" for build, with project type "Dynamically Linked Library (DLL) project"
checked none of the checkboxes below (ATL, MFC, CLR)
specified . dir in the "Include search paths (/I)" in Debug settings
checked "Same as Debug configuration" in "Release settings"
clicked Finish button
This creates couple of VS files in the directory:
mylibrary.sln
mylibrary.vcxproj
mylibrary.vcxproj.filters
mylibrary.vcxproj.user
With a project created this way, I press F6 or select Build | Rebuild solution from the menu.
Then I expect the build to produce the .dll file somewhere, but it does not appear. Only these files appear:
.vs/mylibrary/v15/.suo
.vs/mylibrary/v15/Browse.VC.db
.vs/mylibrary/v15/Browse.VC.opendb
.vs/mylibrary/v15/ipch/AutoPCH/efad7c74cd39331b/EXAMPLE.ipch
Debug/mylibrary.log
Debug/mylibrary.tlog/mylibrary.lastbuildstate
Next, I decided to try creating a fresh new library project, just to observe the differences to get some hints, but that did not help - there were too many differences, even in the file structure...
My questions are:
is my choice of MS Visual C++ a good one for given purpose?
if so, what am I doing wrong here?
I think your steps are probably correct and I think that the right approach to use the code from a C# application. You definitely can call a C++ library from C# by importing the methods.
You missed only to export the methods that you want to use from your library. try using __declspec(dllexport) with these methods. please check this link:
https://msdn.microsoft.com/en-us/library/a90k134d.aspx.
Also, the output should be at the build folder, not the source code folder
Compiling .h files into libraries is ok, the compiler does not care - however, the UI does.
Still, you can tweak this by directly editing the .vcxproj file.
While doing so, make sure that the <ClCompile> sections contain:
<RuntimeLibrary>MultiThreadedDLL</RuntimeLibrary>
Note that you can use commandline for building the DLL project:
"%ProgramFiles(x86)%\Microsoft Visual Studio\2017\Community\MSBuild\15.0\Bin\MSBuild.exe" -target:Clean,Build
(this assumes that your current directory is the one with your .vcxproj)

error LNK1181: cannot open input file 'kernel32.lib'

I have a project on VS 2012. latest SDK is installed on the WIN 8 x64 computer, the project is targeting WIn32.
I have a clean build in Debug, but when I go to release I get the 1181 LNK error - cannot open input file kernel32.lib.
I have the file on the computer in several location, and in the VC directories there is $(WindowsSdkDir_71A)lib and $(WindowsSdkDir)\lib.
Using process monitor I've tried to rebuild and see where devenv.exe is looking for the file
** UPDATE:
In debug it looks in the right place.
in release it doesn't look for the sdk,
but I see this:
Y:\MyProjectFofler\$(LibraryPath)\kernel32.lib PATH NOT FOUND
and also several successful reads from the win8.0 sdk (which should be ok, but the result is the same, and I need it to read from the V7.1A SDK folder...)
What can it be and what might be the solution for this error ?
Thanks.
I ran into this using Visual Studio 2017. I was trying to get the Visual Studio project configurations to reference the external library .lib files I wanted. I managed to trigger this error when I removed any reference to the system libraries. I later figured out this can be corrected by including one of their macro values (though you can specify an absolute direct path, but that's probably not the best coding convention and prone to brittleness).
On the Visual Studio project, right-Clicking on the project item in the Solution explorer panel (not the Solution itself, which is the topmost item), then select Properties. From there do the following:
VC++ Directories --> Library Directories : $(ProjectDir)lib; $(LibraryPath)
Note the $(LibraryPath) value will include extra values such as inherited from parents, and from what I can tell this is a verbose option. My folder project contained a folder called 'lib' which is why I had the first value there before the semicolon.
There are other common options I have used to specify the Library Directories value:
$(VC_LibraryPath_x86)
$(WindowsSDK_LibraryPath_x86)
$(NETFXKitsDir)Lib\um\x86
If you look at the section VC++ Directories --> Library Directories, you can click on the entry line and select 'Edit', then you can watch live previews of what Macros values will be evaluated and resolved to. If you need additional or more specialized values, click on the Macros button to look for more options.
Link to image of Visual Studio 2017 Library Directories configuration

adding a cuda file to an existing c project in visual studio

I am trying to add a CUDA file to my existing C++ Visual Studio project. I have the CUDA 5.0 SDK installed, I have created a new .cu file and also set its Item Type to CUDA/C++ in the CUDA file properties. But it looks like it just does not compile giving errors that say that the compiler does not recognize the CUDA keywords. One of the errors I get is:
error C2065: 'threadIdx' : undeclared identifier
Any suggestions?
I found that the best way to do this is to perform the following in the existing CPU project
1) Build Dependencies -> Build Customisations
click the Cuda checkbox
2) Create a new simple CUDA project using the wizard (you anyway probably want to test your CUDA project builds ok firstly), load both projects into the IDE and then compare settings between the two projects, you will need to add
the following in project settings
$(CudaToolkitLibDir) to additional libraries settings (linker tab)
$(CudaToolkitIncludeDir) to additional include directories (c++ tab)
cudart.lib to additional dependencies (linker tab)
Then compare the CUDA tabs
I found that 32 bit had been pre-selected for the target machine architecture for some reason so I changed that to 64 bit.
After this I added a define _CUDA_CODE_COMPILE_ to preprocessor definitions to switch between CUDA or CPU compilation.
#ifdef _CUDA_CODE_COMPILE_
cudaCodeFunction();
#else
cpuCodeFunction();
#endif
Not ideal but necessary since there seem to be no defines set to indicate that NVCC is installed (other than performing a shell command!)
I can't go through it all at the moment but I think those steps are necessary:
Right click on your Project in the Project Explorer Build...(customization?) [my Version is German. I can't tell the keyword exactly but it's something about "Build...". You need to check "CUDA 5.0" here.
Set up the "Additional Include Directories" for Cuda in the "General" Tab of the Compiler options (Project Properties).
Add the cuda libfile to "Additional Dependencies" in the "Input" Tab of the Linker.
Mark the File as Cuda file (you've done that).
You have to select the right Compiler for the .cu files
Are you following any of the tutorial on how to setup it on visual studio ?
http://blog.norture.com/2012/10/gpu-parallel-programming-in-vs2012-with-nvidia-cuda/