You need to include stdio.h
or cstdio
not 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
-
Edited by
Эти сообщения об ошибках
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
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.
Break points ignored. Nsight message: A CUDA context was created on a GPU that is not currently debuggable. Breakpoints will be disabled. |
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
- CUDA:
cuda_7.5.18_win10.exe
(https://developer.nvidia.com/cuda-75-downloads-archive). Install all options. - Visual Studio Community 2013 with Update 5:
en_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
|
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
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
{1,2,3,4,5} + {10,20,30,40,50} = {11,22,33,44,55} |
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.
Press F10 to step through the lines. The Autos and Call Stack window should update appropriately
{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 thevectorAddCPU.cu
code (https://github.com/siddharthsharmanv/cudacasts/tree/master/YourFirstCUDACProgram).
|
- VS2013 Menu Bar: BUILD -> BUILD
1>------ Build started: Project: vectorAddCPU, Configuration: Debug Win32 ------ |
Run vectorAddCPU (aka. kernel.cu
)
- VS2013 Menu Bar: DEBUG -> Start Without Debugging
|
Try GPU code
- VS2013 Menu Bar: File -> New Project -> Installed -> Templates -> NVIDIA -> CUDA 7.5
- Name the Project helloWorldGPU, click OK
|
Run HelloWorldGPU.cu
|
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%
|
With the VS2013 command prompt, verify nvcc
works
>nvcc --version
|
Navigate to where your CUDA 7.5 Samples
is stored, into the 1_Utililties
directory, in my case: 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
E:CUDACUDA_v7.5Samples1_UtilitiesdeviceQuery> |
Include the header files with nvcc
.
>nvcc -o devQuery -I E:CUDACUDA_v7.5Samplescommoninc deviceQuery.cpp
|
Run devQuery.exe
|
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:
|
Compile
>nvcc -o hello hello.cu
|
Run
>nvcc -o hello hello.cu
|
Errors
Nsight debug problems
Break points ignored. Nsight message: A CUDA context was created on a GPU that is not currently debuggable. Breakpoints will be disabled. |
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>
|
Correct code
#include <stdio.h>
__global__ void foo() {}
int main()
{
foo<<<1,1>>>();
cudaDeviceSynchronize();
printf("CUDA error: %sn", cudaGetErrorString(cudaGetLastError()));
return 0;
}
nvcc -o test test.cu |
Executes normally.
|
CUDA 7.5 cannot use cudaMallocManaged
Using the revised code from https://www.youtube.com/watch?v=2EbHSCvGFM0
Convert VectorAddCPU.cu
to VectorAddGPU.cu
|
Builds correctly.
1>------ Build started: Project: vectorAddGPU, Configuration: Debug Win32 ------ |
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.
|
Running in debug, VS2012 Menu Bar: NSIGHT -> Start CUDA Debugging
Fails on Line 37: a[i] = i;
Unhandled exception at 0x004E152B in vectorAddGPU.exe: 0xC0000005: Access violation writing location 0x00000000. |
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/