Error identifier printf is undefined

While compiling this hello world sample in Ubuntu 10.10 This is from CUDA by Example, chapter 3 (No compile instructions provided >:@) #include __global__ void kernel (void){ }...

You need to include stdio.h or cstdionot iostream (which is for std::cout stuff) for printf (see man 3 printf). I found the source code for the book here.

chapter03/hello_world.cu is actually:


/*
 * Copyright 1993-2010 NVIDIA Corporation.  All rights reserved.
 *
 * NVIDIA Corporation and its licensors retain all intellectual property and 
 * proprietary rights in and to this software and related documentation. 
 * Any use, reproduction, disclosure, or distribution of this software 
 * and related documentation without an express license agreement from
 * NVIDIA Corporation is strictly prohibited.
 *
 * Please refer to the applicable NVIDIA end user license agreement (EULA) 
 * associated with this source code for terms and conditions that govern 
 * your use of this NVIDIA software.
 * 
 */


#include "../common/book.h"

int main( void ) {
    printf( "Hello, World!n" );
    return 0;
}

Where ../common/book.h includes stdio.h.

The README.txt file details how to compile the examples:

The vast majority of these code examples can be compiled quite easily by using 
NVIDIA's CUDA compiler driver, nvcc. To compile a typical example, say 
"example.cu," you will simply need to execute:

> nvcc example.cu

  • Forum
  • General C++ Programming
  • Why isnt this line working in my new pro

Why isnt this line working in my new program?

#include (iostream)

int _tmain(int argc _TCHAR* argv[])
{
int Choice;

printf ( «Welcome to Empty Adventures.nn» );
printf ( «In this game you will be given choicesn»);
printf ( «Good luck brave onen»);

printf ( «/n/n You find yourself in an odd landscape./n»);
printf ( «You find an odd rock on the ground./n»);
printf ( «What do you do?/n»);

On the first printf it says Welcome to Empty Adventures but there is an error. When i go over it it says Error: identifier «printf» is undefined.
Im using c++ Visual Studio 2010.
All the other printf’s are fine. It isnt done and i could use some help.
Can somebody help me?

Last edited on

I don’t understnad what causes your problem directly, but I do see a few things

1. Replace /n with n.
2. int _tmain(int argc _TCHAR* argv[]) should be int _tmain(int argc, _TCHAR* argv[])

Thanks! That might have been the problem the whole time. I will get it fixed up right away

ok it wasnt the problem but thanks for the help.

your iostream should look as follows

#include <iostream>

Even though it is correct, it still won’t help him. He should be including the correct C header for I/O and not the C++ header.

You may have not just copied it to your post, but there is not a } at the end. Everything else I noticed, has already been mentioned.

Topic archived. No new replies allowed.

  • Remove From My Forums
  • Question

  • Brand new, trying to learn C .. installed VS Express 2015 on Win 10 OS desktop .. just using std «Hello World» beginning C program … compiles correctly but for the life of me there is no output display screen with print out «Hello World»
     .. cannot find Win 32 console or using C prompt screen that displays output if that is issue .. very poor documentation on IDE use of Express version .. should I use VS Studio .. very confused .. and beginner .. an help appreciated 

Answers

  • Hi jog1418,

    The MSDN forum has itself policy, we cannot post several question in the same thread. So I would you suggest you re-post new thread about your issue that you encountered.

    Since one thread for one issue, would you please open a new case for this new issue? In this way, our discussion here will not deviate too much from the original issue. This will make answer searching in the forum easier and be beneficial to other community
    members as well.

    If a reply above has solved your issue or doubts, please remember to mark it as answer. Thanks for your understanding.

    Best regards,

    Fletcher


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Edited by

      Wednesday, December 28, 2016 5:49 AM

    • Marked as answer by
      jog1418
      Wednesday, December 28, 2016 10:33 PM

Эти сообщения об ошибках

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

означает, что вы используете имя printf, но компилятор не видит, где было объявлено имя и, соответственно, не знает, что это значит.

Любое имя, используемое в программе, должно быть объявлено до его использования. Компилятор должен знать, что означает это имя.

В этом конкретном случае компилятор не видит объявления с именем printf. Как мы знаем (но не компилятор), это имя стандартной функции C, объявленной в заголовке <stdio.h> в C или в заголовке <cstdio> в С++, и помещается в стандартную (std::) и глобальную (::) ( не обязательно) пространства имен.

Поэтому перед использованием этой функции мы должны предоставить объявление своего имени компилятору, включив соответствующие заголовки.

Например
С

#include <stdio.h>

int main( void )
{
   printf( "Hello Worldn" );
}

С++:

#include <cstdio>

int main()
{
   std::printf( "Hello Worldn" );
   // or printf( "Hello Worldn" );
   // or ::printf( "Hello Worldn" );
}

Иногда причиной такой ошибки является простая опечатка. Например, допустим, что вы определили функцию PrintHello

void PrintHello()
{
    std::printf( "Hello Worldn" );
}

но в основном вы сделали опечатку, а вместо PrintHello вы набрали PrintHello строчной буквой «p».

#include <cstdio>

void PrintHello()
{
    std::printf( "Hello Worldn" );
}

int main()
{
   printHello();
}

В этом случае компилятор выдает такую ​​ошибку, потому что не видит объявления имени PrintHello. PrintHello и PrintHello — это два разных имени, одно из которых было объявлено, а другое не было объявлено, а использовано в теле основного

Что такое необъявленные ошибки идентификатора? Каковы общие причины и как их исправить?

Пример текстов ошибок:

  • Для компилятора Visual Studio: error C2065: 'cout' : undeclared identifier
  • Для компилятора GCC: 'cout' undeclared (first use in this function)

39

Решение

Чаще всего они приходят из-за того, что забывают включить заголовочный файл, содержащий объявление функции, например, эта программа выдаст ошибку «необъявленный идентификатор»:

Отсутствует заголовок

int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}

Чтобы это исправить, мы должны включить заголовок:

#include <iostream>
int main() {
std::cout << "Hello world!" << std::endl;
return 0;
}

Если вы написали заголовок и включили его правильно, заголовок может содержать неправильный включить охрану.

Чтобы узнать больше, смотрите http://msdn.microsoft.com/en-us/library/aa229215(v=vs.60).aspx.

Переменная с ошибкой

Другой распространенный источник ошибки новичка возникает, когда вы неправильно написали переменную:

int main() {
int aComplicatedName;
AComplicatedName = 1;  /* mind the uppercase A */
return 0;
}

Неправильный объем

Например, этот код выдаст ошибку, потому что вам нужно использовать std::string:

#include <string>

int main() {
std::string s1 = "Hello"; // Correct.
string s2 = "world"; // WRONG - would give error.
}

Использовать до объявления

void f() { g(); }
void g() { }

g не был объявлен до его первого использования. Чтобы это исправить, либо переместите определение g до f:

void g() { }
void f() { g(); }

Или добавить декларацию g до f:

void g(); // declaration
void f() { g(); }
void g() { } // definition

stdafx.h не сверху (специфично для VS)

Это зависит от Visual Studio. В VS нужно добавить #include "stdafx.h" перед любым кодом. Код до того, как он игнорируется компилятором, так что если у вас есть это:

#include <iostream>
#include "stdafx.h"

#include <iostream> будет проигнорировано Вам нужно переместить его ниже:

#include "stdafx.h"#include <iostream>

Не стесняйтесь редактировать этот ответ.

54

Другие решения

Рассмотрим похожую ситуацию в разговоре. Представьте, что ваш друг говорит вам: «Боб идет на ужин», а ты не представляешь, кто такой Боб. Вы будете в замешательстве, верно? Твой друг должен был сказать: «У меня есть коллега по работе по имени Боб. Боб подходит к обеду». Теперь Боб объявлен, и вы знаете, о ком говорит ваш друг.

Компилятор выдает ошибку «необъявленный идентификатор», когда вы пытаетесь использовать какой-то идентификатор (который будет именем функции, переменной, класса и т. Д.), И компилятор не видит объявления для него. То есть компилятор понятия не имеет, о чем вы говорите, потому что раньше его не видел.

Если вы получаете такую ​​ошибку в C или C ++, это означает, что вы не сказали компилятору о том, что вы пытаетесь использовать. Объявления часто встречаются в заголовочных файлах, поэтому, скорее всего, это означает, что вы не включили соответствующий заголовок. Конечно, может случиться так, что вы просто не помните, чтобы объявить сущность вообще.

Некоторые компиляторы выдают более конкретные ошибки в зависимости от контекста. Например, пытаясь скомпилировать X x; где тип X не был объявлен с Clang скажет вам «неизвестное имя типа X«. Это гораздо полезнее, потому что вы знаете, что он пытается интерпретировать X как тип. Тем не менее, если у вас есть int x = y;, где y еще не объявлено, он скажет вам «использование необъявленного идентификатора y«потому что есть некоторая двусмысленность в том, что именно y может представлять.

12

У меня была такая же проблема с пользовательским классом, который был определен в пространстве имен. Я пытался использовать класс без пространства имен, вызывая ошибку компилятора «идентификатор» MyClass «не определен».
Добавление

using namespace <MyNamespace>

или используя класс, как

MyNamespace::MyClass myClass;

решил проблему.

5

В C и C ++ все имена должны быть объявлены перед использованием. Если вы попытаетесь использовать имя переменной или функции, которая не была объявлена, вы получите ошибку «необъявленный идентификатор».

Однако функции — это особый случай в C (и только в C), в котором вам не нужно сначала объявлять их. Компилятор C будет предполагать, что функция существует с числом и типом аргументов, как в вызове. Если фактическое определение функции не совпадает, вы получите еще одну ошибку. Этот особый случай для функций не существует в C ++.

Вы исправляете ошибки такого рода, проверяя, что функции и переменные объявлены до их использования. В случае printf вам нужно включить заголовочный файл <stdio.h> (или же <cstdio> в C ++).

Для стандартных функций я рекомендую вам проверить, например, этот справочный сайт, и найдите функции, которые вы хотите использовать. Документация для каждой функции говорит вам, какой заголовочный файл вам нужен.

4

Эти сообщения об ошибках

1.For the Visual Studio compiler: error C2065: 'printf' : undeclared identifier
2.For the GCC compiler: `printf' undeclared (first use in this function)

означает, что вы используете имя printf но компилятор не видит, где было объявлено имя, и, соответственно, не знает, что это значит.

Любое имя, используемое в программе, должно быть объявлено до ее использования. Компилятор должен знать, что обозначает имя.

В этом конкретном случае компилятор не видит объявление имени printf , Как мы знаем (но не компилятор) это имя стандартной функции C, объявленной в заголовке <stdio.h> в C или в заголовке <cstdio> в C ++ и размещены в стандарте (std::) и глобальный (::) (не обязательно) пространства имен.

Поэтому, прежде чем использовать эту функцию, мы должны предоставить объявление ее имени компилятору путем включения соответствующих заголовков.

Например
C:

#include <stdio.h>

int main( void )
{
printf( "Hello Worldn" );
}

C ++:

#include <cstdio>

int main()
{
std::printf( "Hello Worldn" );
// or printf( "Hello Worldn" );
// or ::printf( "Hello Worldn" );
}

Иногда причиной такой ошибки является простая опечатка. Например, давайте предположим, что вы определили функцию PrintHello

void PrintHello()
{
std::printf( "Hello Worldn" );
}

но в основном вы сделали опечатку и вместо PrintHello ты напечатал printHello с строчной буквы «р».

#include <cstdio>

void PrintHello()
{
std::printf( "Hello Worldn" );
}

int main()
{
printHello();
}

В этом случае компилятор выдаст такую ​​ошибку, потому что он не видит объявление имени printHello, PrintHello а также printHello два разных имени, одно из которых было объявлено, а другое не объявлено, но используется в теле основного

3

Это похоже на использование функции без ее объявления. заголовочный файл будет содержать
функция printf (). Включите заголовочный файл в вашу программу, это решение для этого.
Некоторые пользовательские функции могут также вызывать ошибки, если они не были объявлены перед использованием. Если
это используется во всем мире без проб.

0

В большинстве случаев, если вы уверены, что импортировали данную библиотеку, Visual Studio поможет вам с IntelliSense.

Вот что сработало для меня:

Удостоверься что #include "stdafx.h" объявляется первым, то есть вверху всех ваших включений.

0

CUDA 7.5 logo

I needed to compile and debug a CUDA «.cu» file on my Windows 10 Pro with a Nvidia Quadra 2000 GPU card (yes, an old HP Z600 workstation with an old GPU).  Installing CUDA 10.2, the last Quadro 2000 driver (377.83 from 2017) with Visual Studio 2019 worked great. 

Until I needed to debug.

Nsight unable to debug error

Break points ignored. Nsight message: A CUDA context was created on a GPU that is not currently debuggable. Breakpoints will be disabled.
Adapter: Quadro 2000

After some trail and error (errors at the bottom of this blog entry) I have a working environment that can debug in Visual Studio and compile on the command line.  This required going back in time and using executables released more than five years ago.  Luckily all of the problems I encounter have been long solved and easily searched online.  

I first had to determine that the Nvidia Quadro 2000 GPU was a Fermi microarchitecture (https://en.wikipedia.org/wiki/CUDA).  The last Nsight version (used for CUDA debugging) that works with Fermi is Nsight 4.7, which comes with CUDA 7.5.  This means features in GPUs > Fermi will not work in this environment (i.e. feature callMallocManaged).

Install

  • CUDAcuda_7.5.18_win10.exe (https://developer.nvidia.com/cuda-75-downloads-archive).  Install all options.
  • Visual Studio Community 2013 with Update 5en_visual_studio_community_2013_with_update_5_x86_6816332.exe   (https://my.visualstudio.com/Downloads?q=visual%20studio%202013&wt.mc_id=o~msft~vscom~older-downloads)
  • VS Build Tools 2013 (for command line access): BuildTools_Full.exe  (https://www.microsoft.com/en-us/download/confirmation.aspx?id=40760) Be sure to install the command line interface (CLI).

Verify Visual Studio 2013 works with CUDA .cu files and GPU

Following:  https://riptutorial.com/cuda

In VS2013 Menu Bar:  File -> Open -> Project Solution,  Open the CUDA samples Samples_vs2013.sln.

  • In the Solution Explorer (panel on right hand side), Highlight 1_Utilities -> DeviceQuery
  • Right-click, Build Solution
  • VS2013 Menu Bar:  DEBUG -> Start Without Debugging
Result (success) DeviceQuery.cpp

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery../../bin/win64/Debug/deviceQuery.exe Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "Quadro 2000"
  CUDA Driver Version / Runtime Version          7.5 / 7.5
  CUDA Capability Major/Minor version number:    2.1
  Total amount of global memory:                 1024 MBytes (1073741824 bytes)
  ( 4) Multiprocessors, ( 48) CUDA Cores/MP:     192 CUDA Cores
  GPU Max Clock rate:                            1251 MHz (1.25 GHz)
  Memory Clock rate:                             1304 Mhz
  Memory Bus Width:                              128-bit
  L2 Cache Size:                                 262144 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65535), 3D=(2048, 2048, 2048)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 32768
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  1536
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (65535, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 1 copy engine(s)
  Run time limit on kernels:                     Yes
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  CUDA Device Driver Mode (TCC or WDDM):         WDDM (Windows Display Driver Model)
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 15 / 0
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 7.5, CUDA Runtime Version = 7.5, NumDevs = 1, Device0 = Quadro 2000
Result = PASS
Press any key to continue . . .

Verify Visual Studio 2013 CUDA debugging

Creating a new CUDA project —  https://www.youtube.com/watch?v=2EbHSCvGFM0

VS2013 Menu Bar:  File -> New Project -> Installed -> Templates -> NVIDIA -> CUDA 7.5

 Name the Project checkDebug, click OK

Visual Studio new Nvidia CUDA project

Build and run the kernel.cu without debugging (let’s see it works first).

  • VS2013 Menu Bar: BUILD -> Build Solution
  • VS2013 Menu Bar: DEBUG -> Start Without Debugging
Result (success): checkDebug

{1,2,3,4,5} + {10,20,30,40,50} = {11,22,33,44,55}
Press any key to continue . . .

Run with debugging

  • In kernel.cu, set a breakpoint on line 18:  const int arraySize = 5;
    • (highlight code F9, or right click in far left column)
  • VS2013 Menu Bar:  NSIGHT -> Start CUDA Debugging

Nsight will start (will require Administrator privileges to launch), the green icon will appear in the taskbar.

Nsight running icon

Press F10 to step through the lines.  The Autos and Call Stack window should update appropriately

Result (success)

{1,2,3,4,5} + {10,20,30,40,50} = {11,22,33,44,55}

Create custom CUDA code in Visual Studio 2013

Try CPU code only

  • VS2013 Menu Bar:  File -> New Project -> Installed -> Templates -> NVIDIA -> CUDA 7.5
  • Name the Project vectorAddCPU, click OK
  • Delete the code in kernel.cu and copy/paste with the vectorAddCPU.cu code  (https://github.com/siddharthsharmanv/cudacasts/tree/master/YourFirstCUDACProgram).
 vectorAddCPU.cu

#include <stdio.h>
#define SIZE    1024

void VectorAdd(int *a, int *b, int *c, int n)
{
    int i;

    for (i=0; i < n; ++i)
        c[i] = a[i] + b[i];
}

int main()
{
    int *a, *b, *c;

    
    a = (int *)malloc(SIZE * sizeof(int));
    b = (int *)malloc(SIZE * sizeof(int));
    c = (int *)malloc(SIZE * sizeof(int));

    
    for (int i = 0; i < SIZE; ++i)
    {
        a[i] = i;
        b[i] = i;
        c[i] = 0;
    }

    
    VectorAdd(a, b, c, SIZE);

    for (int i = 0; i < 10; ++i)
        printf("c[%d] = %dn", i, c[i]);

    free(a);
    free(b);
    free(c);

    return 0;
}

  • VS2013 Menu Bar: BUILD -> BUILD
Build (success): vectorAddCPU

1>------ Build started: Project: vectorAddCPU, Configuration: Debug Win32 ------
1>  Compiling CUDA source file kernel.cu...
1>  
1>  E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddCPUvectorAddCPU>"E:CUDACUDA_v7.5Toolkitbinnvcc.exe" -gencode=arch=compute_20,code="sm_20,compute_20" --use-local-env --cl-version 2013 -ccbin "E:Microsoft Visual Studio2013VCbin"  -IE:CUDACUDA_v7.5Toolkitinclude -IE:CUDACUDA_v7.5Toolkitinclude  -G   --keep-dir Debug -maxrregcount=0  --machine 32 --compile -cudart static  -g   -DWIN32 -D_DEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /Od /Zi /RTC1 /MDd " -o Debugkernel.cu.obj "E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddCPUvectorAddCPUkernel.cu"
1>  kernel.cu
1>  vectorAddCPU.vcxproj -> E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddCPUDebugvectorAddCPU.exe
1>  copy "E:CUDACUDA_v7.5Toolkitbincudart*.dll" "E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddCPUDebug"
1>  E:CUDACUDA_v7.5Toolkitbincudart32_75.dll
1>  E:CUDACUDA_v7.5Toolkitbincudart64_75.dll
1>          2 file(s) copied.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

Run vectorAddCPU (aka. kernel.cu)

  • VS2013 Menu Bar:  DEBUG -> Start Without Debugging
Result (success): run vectorAddCPU.exe

c[0] = 0
c[1] = 2
c[2] = 4
c[3] = 6
c[4] = 8
c[5] = 10
c[6] = 12
c[7] = 14
c[8] = 16
c[9] = 18
Press any key to continue . . .

Try GPU code

  • VS2013 Menu Bar:  File -> New Project -> Installed -> Templates -> NVIDIA -> CUDA 7.5
  • Name the Project helloWorldGPU, click OK
HelloWorldGPU.cu

#include<stdio.h>
#include<stdlib.h>

__global__ void print_from_gpu(void) {
    printf("Hello World! from thread [%d,%d]
        From devicen", threadIdx.x, blockIdx.x);
}

int main(void) {
    printf("Hello World from host!n");
    print_from_gpu << <1, 1 >> >();
    cudaDeviceSynchronize();
    return EXIT_SUCCESS;
}

Run HelloWorldGPU.cu

Result (success): HelloWorldGPU.exe

Hello World from host!
Hello World! from thread [0,0]                     From device
Press any key to continue . . .

Verify CUDA from command line

If missing, find the Visual Studio 2013 command prompt (https://stackoverflow.com/questions/21476588/where-is-developer-command-prompt-for-vs2013 )
Look in:  C:ProgramDataMicrosoftWindowsStart MenuProgramsVisual Studio 2013

Verify that CUDA appears in the PATH

>echo %PATH%

CUDA in VS2013 Command Prompt Path

E:Microsoft Visual Studio2013>echo %PATH%
E:Microsoft Visual Studio2013Common7IDECommonExtensionsMicrosoftTestWindow;C:Program Files (x86)Microsoft SDKsF#3.1Frameworkv4.0;C:Program Files (x86)Microsoft SDKsTypeScript1.0;C:Program Files (x86)MSBuild12.0bin;E:Microsoft Visual Studio2013Common7IDE;E:Microsoft Visual Studio2013VCBIN;E:Microsoft Visual Studio2013Common7Tools;C:WINDOWSMicrosoft.NETFrameworkv4.0.30319;E:Microsoft Visual Studio2013VCVCPackages;C:Program Files (x86)HTML Help Workshop;E:Microsoft Visual Studio2013Team ToolsPerformance Tools;C:Program Files (x86)Windows Kits8.1binx86;C:Program Files (x86)Microsoft SDKsWindowsv8.1AbinNETFX 4.5.1 Tools;E:CUDACUDA_v7.5Toolkitbin;E:CUDACUDA_v7.5Toolkitlibnvvp;;;;;;C:WINDOWSsystem32;C:WINDOWS;C:WINDOWSSystem32Wbem;C:WINDOWSSystem32WindowsPowerShellv1.0;C:WINDOWSSystem32OpenSSH;E:Microsoft Visual Studio2019CommunityVCToolsMSVC14.25.28610binHostx64x64;C:Usersadminroot.dnxbin;C:Program FilesMicrosoft DNXDnvm;C:Program FilesMicrosoft SQL Server110ToolsBinn;C:Program Files (x86)Microsoft SDKsTypeScript1.0;C:Program Files (x86)NVIDIA CorporationPhysXCommon;C:Program FilesMicrosoft SQL Server120ToolsBinn;C:Usersaholi_000AppDataLocalMicrosoftWindowsApps;

E:Microsoft Visual Studio2013>

With the VS2013 command prompt, verify nvcc works

>nvcc --version

Result (success) nvcc —version

E:Microsoft Visual Studio2013>nvcc --version
nvcc: NVIDIA (R) Cuda compiler driver
Copyright (c) 2005-2015 NVIDIA Corporation
Built on Tue_Aug_11_14:49:10_CDT_2015
Cuda compilation tools, release 7.5, V7.5.17

E:Microsoft Visual Studio2013>

Navigate to where your CUDA 7.5 Samples is stored, into the 1_Utililties directory, in my case:  E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery

Navigate to deviceQuery.cu

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>dir
 Volume in drive E is Data
 Volume Serial Number is AAD3-8C76

 Directory of E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery

04/30/2020  10:02 AM    <DIR>          .
04/30/2020  10:02 AM    <DIR>          ..
05/27/2015  04:39 PM            13,208 deviceQuery.cpp
08/16/2015  02:32 PM               871 deviceQuery_vs2010.sln
08/16/2015  02:32 PM             4,712 deviceQuery_vs2010.vcxproj
08/16/2015  02:32 PM               871 deviceQuery_vs2012.sln
08/16/2015  02:32 PM             4,757 deviceQuery_vs2012.vcxproj
04/29/2020  01:38 PM        18,219,008 deviceQuery_vs2013.sdf
04/29/2020  11:58 AM               950 deviceQuery_vs2013.sln
04/27/2020  09:39 AM             4,753 deviceQuery_vs2013.vcxproj
08/16/2015  02:32 PM               176 readme.txt
04/29/2020  11:12 AM    <DIR>          x64
              13 File(s)     18,449,834 bytes
               3 Dir(s)  1,450,845,192,192 bytes free

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>

Try running and compiling CUDA sample DeviceQuery.cpp

>nvcc -o testDevQuery deviceQuery.cpp

Error: fatal error C1083: Cannot open include file: 'helper_cuda.h': No such file or directory

nvcc compile failure: missing helper_cuda.h

E:Microsoft Visual Studio2013>cd CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>dir
 Volume in drive E is Data
 Volume Serial Number is AAD3-8C76

 Directory of E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery

04/29/2020  01:38 PM    <DIR>          .
04/29/2020  01:38 PM    <DIR>          ..
05/27/2015  04:39 PM            13,208 deviceQuery.cpp
08/16/2015  02:32 PM               871 deviceQuery_vs2010.sln
08/16/2015  02:32 PM             4,712 deviceQuery_vs2010.vcxproj
08/16/2015  02:32 PM               871 deviceQuery_vs2012.sln
08/16/2015  02:32 PM             4,757 deviceQuery_vs2012.vcxproj
04/29/2020  01:38 PM        18,219,008 deviceQuery_vs2013.sdf
04/29/2020  11:58 AM               950 deviceQuery_vs2013.sln
04/27/2020  09:39 AM             4,753 deviceQuery_vs2013.vcxproj
04/29/2020  12:14 PM           198,144 devQuery.exe
04/29/2020  12:14 PM               648 devQuery.exp
04/29/2020  12:14 PM             1,736 devQuery.lib
08/16/2015  02:32 PM               176 readme.txt
04/29/2020  11:12 AM    <DIR>          x64
              12 File(s)     18,449,834 bytes
               3 Dir(s)  1,450,922,340,352 bytes free

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>nvcc -o devQuery deviceQuery.cpp
deviceQuery.cpp
deviceQuery.cpp(20) : fatal error C1083: Cannot open include file: 'helper_cuda.h': No such file or directory

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>

Include the header files with nvcc.

>nvcc -o devQuery -I E:CUDACUDA_v7.5Samplescommoninc  deviceQuery.cpp

nvcc compile success

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>nvcc -o devQuery -I E:CUDACUDA_v7.5Samplescommoninc  deviceQuery.cpp
deviceQuery.cpp
   Creating library devQuery.lib and object devQuery.exp

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>dir
 Volume in drive E is Data
 Volume Serial Number is AAD3-8C76

 Directory of E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery

04/30/2020  10:02 AM    <DIR>          .
04/30/2020  10:02 AM    <DIR>          ..
05/27/2015  04:39 PM            13,208 deviceQuery.cpp
08/16/2015  02:32 PM               871 deviceQuery_vs2010.sln
08/16/2015  02:32 PM             4,712 deviceQuery_vs2010.vcxproj
08/16/2015  02:32 PM               871 deviceQuery_vs2012.sln
08/16/2015  02:32 PM             4,757 deviceQuery_vs2012.vcxproj
04/29/2020  01:38 PM        18,219,008 deviceQuery_vs2013.sdf
04/29/2020  11:58 AM               950 deviceQuery_vs2013.sln
04/27/2020  09:39 AM             4,753 deviceQuery_vs2013.vcxproj
04/30/2020  10:04 AM           198,144 devQuery.exe
04/30/2020  10:04 AM               648 devQuery.exp
04/30/2020  10:04 AM             1,736 devQuery.lib
04/30/2020  10:02 AM                 0 nvcc
08/16/2015  02:32 PM               176 readme.txt
04/29/2020  11:12 AM    <DIR>          x64
              13 File(s)     18,449,834 bytes
               3 Dir(s)  1,450,922,340,352 bytes free

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>

Run devQuery.exe

Result (success): devQuery.exe

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>devQuery.exe
devQuery.exe Starting...

 CUDA Device Query (Runtime API) version (CUDART static linking)

Detected 1 CUDA Capable device(s)

Device 0: "Quadro 2000"
  CUDA Driver Version / Runtime Version          7.5 / 7.5
  CUDA Capability Major/Minor version number:    2.1
  Total amount of global memory:                 1024 MBytes (1073741824 bytes)
  ( 4) Multiprocessors, ( 48) CUDA Cores/MP:     192 CUDA Cores
  GPU Max Clock rate:                            1251 MHz (1.25 GHz)
  Memory Clock rate:                             1304 Mhz
  Memory Bus Width:                              128-bit
  L2 Cache Size:                                 262144 bytes
  Maximum Texture Dimension Size (x,y,z)         1D=(65536), 2D=(65536, 65535), 3D=(2048, 2048, 2048)
  Maximum Layered 1D Texture Size, (num) layers  1D=(16384), 2048 layers
  Maximum Layered 2D Texture Size, (num) layers  2D=(16384, 16384), 2048 layers
  Total amount of constant memory:               65536 bytes
  Total amount of shared memory per block:       49152 bytes
  Total number of registers available per block: 32768
  Warp size:                                     32
  Maximum number of threads per multiprocessor:  1536
  Maximum number of threads per block:           1024
  Max dimension size of a thread block (x,y,z): (1024, 1024, 64)
  Max dimension size of a grid size    (x,y,z): (65535, 65535, 65535)
  Maximum memory pitch:                          2147483647 bytes
  Texture alignment:                             512 bytes
  Concurrent copy and kernel execution:          Yes with 1 copy engine(s)
  Run time limit on kernels:                     Yes
  Integrated GPU sharing Host Memory:            No
  Support host page-locked memory mapping:       Yes
  Alignment requirement for Surfaces:            Yes
  Device has ECC support:                        Disabled
  CUDA Device Driver Mode (TCC or WDDM):         WDDM (Windows Display Driver Model)
  Device supports Unified Addressing (UVA):      Yes
  Device PCI Domain ID / Bus ID / location ID:   0 / 15 / 0
  Compute Mode:
     < Default (multiple host threads can use ::cudaSetDevice() with device simultaneously) >

deviceQuery, CUDA Driver = CUDART, CUDA Driver Version = 7.5, CUDA Runtime Version = 7.5, NumDevs = 1, Device0 = Quadro 2000
Result = PASS

E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery>

Create and Run New Project from Command Line

  • Create a new file hello.cu (https://riptutorial.com/cuda/example/9316/let-s-launch-a-single-cuda-thread-to-say-hello)
  • Using the VS2013 command prompt, compile and run
    • Make sure to include the necessary headers from the CUDA toolkit: 
hello.c

#include <stdio.h>

// __global__ functions, or "kernels", execute on the device
__global__ void hello_kernel(void)
{
  printf("Hello, world from the device!n");
}

int main(void)
{
  // greet from the host
  printf("Hello, world from the host!n");

  // launch a kernel with a single thread to greet from the device
  hello_kernel<<<1,1>>>();

  // wait for the device to finish so that we see the message
  cudaDeviceSynchronize();

  return 0;
}

Compile

>nvcc -o hello hello.cu

Build (success) hello.cu

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envhello>nvcc -o hello hello.cu
hello.cu
   Creating library hello.lib and object hello.exp

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envhello>

Run

>nvcc -o hello hello.cu

Result (success) hello.cu

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envhello>hello
Hello, world from the host!
Hello, world from the device!

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envhello>

Errors

Nsight debug problems

Nsight unable to debug error

Break points ignored. Nsight message: A CUDA context was created on a GPU that is not currently debuggable. Breakpoints will be disabled.
Adapter: Quadro 2000

My Nsight 5.2 doesn’t work with Fermi family GPUs (i.e. Quadro 2000)

https://stackoverflow.com/questions/43030274/a-cuda-context-was-created-on-a-gpu-that-is-not-currently-debuggable
 

Missing #include <stdio.h>

nvcc compile (fails): missing stdio.h

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envtest>nvcc -o test test.cu
test.cu
test.cu(8): error: identifier "printf" is undefined

1 error detected in the compilation of "C:/Users/AHOLI_~1/AppData/Local/Temp/tmpxft_000020dc_00000000-6_test.cpp4.ii".

Correct code

#include <stdio.h>

__global__ void foo() {}

int main()
{
  foo<<<1,1>>>();

  cudaDeviceSynchronize();
  printf("CUDA error: %sn", cudaGetErrorString(cudaGetLastError()));

  return 0;
}

test.bat

nvcc -o test test.cu

Executes normally.

Result (success): test.exe

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envtest>test.bat

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envtest>nvcc -o test test.cu
test.cu
   Creating library test.lib and object test.exp

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envtest>test
CUDA error: no error

E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev Envtest>

CUDA 7.5 cannot use cudaMallocManaged

Using the revised code from https://www.youtube.com/watch?v=2EbHSCvGFM0

Convert VectorAddCPU.cu to VectorAddGPU.cu

VectorAddGPU.cu

#include <stdio.h>
#define SIZE    1024

__global__ void VectorAdd(int *a, int *b, int *c, int n)
{

    int i = threadIdx.x;

    if (i < n)
        c[i] = a[i] + b[i];
}

__global__ void print_from_gpu(void) {
    printf("Hello World! from thread [%d,%d]
        From devicen", threadIdx.x, blockIdx.x);
}

int main()
{
    int *a, *b, *c;

    printf("Hello World from host!n");
    print_from_gpu << <1, 1 >> >();
    cudaDeviceSynchronize();

    cudaMallocManaged(&a, SIZE * sizeof(int));
    cudaMallocManaged(&b, SIZE * sizeof(int));
    cudaMallocManaged(&c, SIZE * sizeof(int));

    printf("passed cudaMallocManagedn");

    for (int i = 0; i < SIZE; ++i)
    {
        a[i] = i;
        b[i] = i;    
        c[i] = 0;
    }

    printf("passed var addition");

    VectorAdd <<<1, SIZE>>> (a, b, c, SIZE);
    cudaDeviceSynchronize();

    for (int i = 0; i < 10; ++i)
        printf("c[%d] = %dn", i, c[i]);

    cudaFree(a);
    cudaFree(b);
    cudaFree(c);

    return 0;
}

Builds correctly.

Build (success): VectorAddGPU.cu

1>------ Build started: Project: vectorAddGPU, Configuration: Debug Win32 ------
1>  Compiling CUDA source file vectorAddGPU.cu...
1>  
1>  E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddGPUvectorAddGPU>"E:CUDACUDA_v7.5Toolkitbinnvcc.exe" -gencode=arch=compute_20,code="sm_20,compute_20" --use-local-env --cl-version 2013 -ccbin "E:Microsoft Visual Studio2013VCbin"  -IE:CUDACUDA_v7.5Toolkitinclude -IE:CUDACUDA_v7.5Toolkitinclude  -G   --keep-dir Debug -maxrregcount=0  --machine 32 --compile -cudart static  -g   -DWIN32 -D_DEBUG -D_CONSOLE -D_MBCS -Xcompiler "/EHsc /W3 /nologo /Od /Zi /RTC1 /MDd " -o DebugvectorAddGPU.cu.obj "E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddGPUvectorAddGPUvectorAddGPU.cu"
1>  vectorAddGPU.cu
1>  vectorAddGPU.vcxproj -> E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddGPUDebugvectorAddGPU.exe
1>  copy "E:CUDACUDA_v7.5Toolkitbincudart*.dll" "E:ProjectsCudaTest (VisualStudio)CUDA 7.5 - Check Dev EnvvectorAddGPUDebug"
1>  E:CUDACUDA_v7.5Toolkitbincudart32_75.dll
1>  E:CUDACUDA_v7.5Toolkitbincudart64_75.dll
1>          2 file(s) copied.
========== Build: 1 succeeded, 0 failed, 0 up-to-date, 0 skipped ==========

VS2012 Menu Bar:  DEBUG -> Start Without Debugging

Correct answer should be as listed at top of blog for VectorAddCPU.cu

Does not return correct answer.

Result (failure): VectorAddGPU.exe

Hello World from host!
Hello World! from thread [0,0]                     From device
passed cudaMallocManaged
Press any key to continue . . .

Running in debug, VS2012 Menu Bar: NSIGHT -> Start CUDA Debugging

Fails on Line 37:  a[i] = i;

Unhandled Exception

Unhandled exception at 0x004E152B in vectorAddGPU.exe: 0xC0000005: Access violation writing location 0x00000000.

Unhandled Exception

Variable «a» is never initalized.

Related to Quadro 2000 is a CUDA 2.1 compute capability and cudaMallocManaged is CUDA >=3.0 compute capability
http://selkie.macalester.edu/csinparallel/modules/TimingCUDA/build/html/0-Introduction/Introduction.html

cudaMemcpy, cudaMemcpyHostToDevice, cudaMemcpyDeviceToHost must be used instead of cudaMallocManaged on CUDA 7.5

 https://cuda-tutorial.readthedocs.io/en/latest/tutorials/tutorial01/
    // Transfer data from host to device memory
    cudaMemcpy(d_a, a, sizeof(float) * N, cudaMemcpyHostToDevice);

 

Links

  • CUDA microarchitecture — https://en.wikipedia.org/wiki/CUDA
  • Getting started with cuda — https://riptutorial.com/cuda
  • Getting started with CUDA on Windows — http://developer.download.nvidia.com/compute/cuda/6_5/rel/docs/CUDA_Getting_Started_Windows.pdf
  • Tutorial 01: Say Hello to CUDA — https://cuda-tutorial.readthedocs.io/en/latest/tutorials/tutorial01/
  • An Even Easier Introduction to CUDA — https://devblogs.nvidia.com/even-easier-introduction-cuda/

Понравилась статья? Поделить с друзьями:
  • Error identifier not found utf8tosys
  • Error identifier not found try
  • Error identifier not found result
  • Error identifier not found power
  • Error identifier not found lazarus