9

I am trying to learn c++ but most of the tutorials and books I have read or looked up teaches you this...

(I am assuming like most tutorials, they are teaching in the beginning to code either in win32 console or CLR console. In either case the following does not work.)

#include <iostream>
int main(  )
{
    std::cout << "Hello World\n";
    return (0);
}

The IDE that i have is Visual C++ 2008 Express edition and they accept code like this

#include "stdafx.h"


int _tmain(int argc, _TCHAR* argv[])
{
    return 0;
}

Or like this

#include "stdafx.h"

using namespace System;

int main(array<System::String ^> ^args)
{
    Console::WriteLine(L"Hello World");
    return 0;
}

Honestly I do not no the difference in none of these and I am not sure if I should just download a older compiler so that it works. If someone can tell me what the difference in these are and where to go from there. That will help tremendously. Thanks [Edited]

I am trying to do a simple hello world. But I get the error "system can not find path specified." I have screenshot that shows what the error looks like. It also is saying that my project is out of date when I clearly save the file before I build it. Apparently it can not find the executable file. I went to the debug fold and did not see any .exe file.

Screenshot

Screenshot

[Edited]

Ok, now When I try to build the project I get the following errors

1>------ Rebuild All started: Project: test, Configuration: Debug Win32 ------
1>Deleting intermediate and output files for project 'test', configuration 'Debug|Win32'
1>Compiling...
1>stdafx.cpp
1>Compiling...
1>test.cpp
1>c:\users\numerical25\desktop\test\test\test.cpp(1) : warning C4627: '#include <iostream>': skipped when looking for precompiled header use
1>        Add directive to 'stdafx.h' or rebuild precompiled header
1>c:\users\numerical25\desktop\test\test\test.cpp(6) : error C2653: 'std' : is not a class or namespace name
1>c:\users\numerical25\desktop\test\test\test.cpp(6) : error C2065: 'cout' : undeclared identifier
1>Build log was saved at "file://c:\Users\numerical25\Desktop\test\test\Debug\BuildLog.htm"
1>test - 2 error(s), 1 warning(s)
========== Rebuild All: 0 succeeded, 1 failed, 0 skipped ==========

Here is the code I used

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

int main(  )
{
    std::cout << "Hello World\n";
    return (0);
}

Note: I tried using it with and without the #include "stdafx.h" When I tried it without the #include "stdafx.h", it said I might be missing it.

Adaline Simonian
  • 4,596
  • 2
  • 24
  • 35
numerical25
  • 10,524
  • 36
  • 130
  • 209

11 Answers11

19

Not sure what you're asking. The first two examples you gave are valid C++ programs that should (will) compile with VC++. The third example is a C++/CLI program that must be compiled with the /CLR compiler switch (this is called Managed C++).

EDIT: Adding more specific information (from a comment below):

The first two examples are standard (native) C++ (albeit, the second example has MS-proprietary macros). They compile to native code. The third is C++/CLI (a "managed" extension to C++). It compiles to managed (.NET) code. Only the third snippet interacts with the .NET framework in any way. All three are absolutely buildable and runnable using the appropriate projects in VS 2008 (no command line necessary)!

Based on your latest update, it looks like you have probably modified some project properties and changed some paths. The app is building, but when you try to run it via VS (you should do this with <Ctrl>+F5, by the way), the executable cannot be found (there are several ways you could have messed this up by changing or playing with various settings).

Please note the difference between building and running. Building is the process of compiling and linking your source code. Running is launching the resulting executable. You seem to be confused between these (judging from your complaints about the "...out of date" dialog box). It is normal to get the "...out of date" dialog box if you try to run without rebuilding after you have made a change to the project (even if that change is saved). Just make sure you click "yes." You need to build the project before you can run it.

My recommendation is to completely delete your project and solution. Create a new empty project, as suggested elsewhere in this now-very-heavyweight thread, and don't modify any project settings. If this doesn't work, something is seriously wrong!

ANOTHER EDIT: Just for completion, since this question kept changing:

As others have already pointed out, your ultimate problem with the first snippet is the use of precompiled headers (PCH). PCH are turned on by default in new VS C++ projects. Their purpose is to speed compilation when many implementation files include the same set of headers -- preventing the compiler from having to parse the header files for each compilation unit.

You have three options:

  1. (Recommended) Disable PCH -- Project Properties --> Configuration Properties --> C/C++ --> Precompiled Headers: Set Create/Use Precompiled Header to Not Using Precompiled Headers. (You don't need to do anything with the "stdafx.h" file or the #include for it.)
  2. Place your commonly used #includes in "stdafx.h". In your case, you would put #include <iostream> in "stdafx.h".
  3. Place your #includes after `#include "stdafx.h". Microsoft requires that the "stdafx.h" be the first included file in a compilation unit.
  • 2
    Wow! An answer that's actually correct! That seems to be rare on this question. – Billy ONeal Feb 21 '10 at 05:49
  • Unless something horribly exploded, or likely an option isn't set correctly, they'd work. +1 – Xorlev Feb 21 '10 at 08:06
  • @BillyONeal: For a given value of "correct". Last I checked, `_tmain` and `_TCHAR` were not part of the C++ standard. The second one is accepted by VC++ yes, but valid C++? – jalf Feb 21 '10 at 14:42
  • 1
    Yes, because _tmain and _TCHAR are just macros that expand to main and char, respectively. Macros are certainly part of the standard, and so long as you don't define MS specific stuff in your file, the preprocessor will convert that file into plain C++. – Billy ONeal Feb 21 '10 at 17:57
  • Yea I am one step ahead of you. I've actually created about 7 projects and I saved them everywhere. Still get it. I havn't change any settings cause I havnt had it for long. The first thing I ever did in this compiler was copy and paste that code – numerical25 Feb 21 '10 at 20:26
  • I am going to try and reinstall everything and you will hear about from me afterwards and i will let you know what happened. Thanks – numerical25 Feb 21 '10 at 20:27
  • I reinstalled it and I got the same error. But I think you are right. I might have been getting the build / rebuild mixed up with actually running the program. But anyways I build it first and I got some other error. I updated my question. – numerical25 Feb 21 '10 at 21:56
7

A minor point, which I don't see elsewhere in the answers: When using precompiled headers, such as your stdafx.h, you need to include them first. Change it to:

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

and that should fix the errors about it.

Alternatively, it may be easier to simply switch off precompiled headers: Project > Properties > Configuration Properties > C/C++ > Precompiled Headers > Switch first option to "Not using precompiled headers". They can be useful for big projects but will just be awkward and annoying while you're learning, since they have extra rules (like this "must be included first") which aren't requirements of standard C++ .

Peter
  • 7,216
  • 2
  • 34
  • 46
  • I didn't see your answer before I figured it out but you came the closest to what was wrong. – numerical25 Feb 21 '10 at 22:14
  • also that is a very useful tip to turn off precompiled headers – numerical25 Feb 21 '10 at 22:20
  • Beat me to it. He finally posts enough information after a day to actually diagnose what is wrong, and you sneak in for the win! Congrats. :) –  Feb 22 '10 at 01:03
  • The quick and the dead... I'll give you an upvote for a consolation prize though ;-) – Peter Feb 22 '10 at 03:10
4

The "difference" is pedantic. The latter are just Microsoft-specific entry points.

As you are learning C++, I recommend you use a compiler, and preferably an operating system that lets you focus on C++, and not the platform. For this I recommend g++, on an Linux distribution such as Ubuntu.

Try this tutorial, there are many others that are similar that quickly let you overcome being tied to the tools, and focus on C++.

Matt Joiner
  • 112,946
  • 110
  • 377
  • 526
  • 5
    A whole new OS is somewhat a sledge-hammer to crack a nut. There is nothing preventing the compilation of ISO C++ code on VC++ 2008 Express. I don't think he needs yet another tutorial. – Clifford Feb 21 '10 at 09:03
  • 1
    The last One is C++/CLI which is a new language by itselg, however close to C++. – kriss Feb 21 '10 at 09:03
  • 2
    Yes, however having been in his position, I have 2 major concerns: Absolutely minimal C++ must be learnt (no mention of CLR/CLI, or even Windows should be made), and secondly that IDEs only clutter the mindset in learning a language. The use of C++ becomes associated with Visual Studio, and a dependency forms. No VS, and the programmer cannot produce C++. This is learning MSVC++, not pure C++. A C++ developer **must** understand everything from the operating system call interface upwards to be effective. – Matt Joiner Feb 21 '10 at 11:14
  • What's the problem? Just write the code with whichever editor he wants and compile it with the command-line version of VC++ (cl.exe). – Matteo Italia Feb 21 '10 at 11:37
  • -1: exact duplicate of C.D. Reimer's answer, which was heavily unpopular for the same reason! Sounds like maybe he should just write his own compiler and linker while he's at it. I mean he really **must** understand how the compiler works. No compiler, and the programmer cannot produce C++! How many C++ developers have you worked with that "understand everything?" I'd like to move to your planet. –  Feb 21 '10 at 17:03
  • This answer is nothing like C.D Reimer's answer. I'm sorry your planetary immigration was denied, join us sometime. – Matt Joiner Feb 21 '10 at 17:33
  • @Matt: nothing like it, except that it recommends a different development environment and dodges the question. What is your aversion to *tools*? It is precisely the tools that allow a newcomer to *focus on the language*, and for that VS is one of the best. It is more of a hinderance to experts. Furthermore, the differences are hardly "pedantic." The third snippet is a different language entirely. Your viewpoint is very naive. –  Feb 21 '10 at 17:59
  • Why must a C++ developer "understand everything from the operating system call interface upwards to be effective"? Id does not stop Java from being an effective tool? The .NET framework effectively [i]is[/i] the OS API (at least it is the API MS would prefer you use where possible). – Clifford Feb 21 '10 at 18:07
  • 1
    VS does allow you to focus on the problem to a degree. For the absolute beginner, I don't believe "click on this button, perform this incantation" covers it however. The beginner needs to understand the compiling, and linking stage, as well as use unadorned entry points, as per the OPs confusion. After some considerable advance beyond the OPs current skill level, VS can be substituted to perform the more repetitive stuff. – Matt Joiner Feb 21 '10 at 21:57
  • 1
    The C++ developer is using the last of the mainstream industrially used systems programming languages (accepting that C and other alternatives are not _preferred_ in high-level applications development). Careful attention and knowledge is required to interact safely and efficiently with the varying operating system interfaces: This variety is not present with the effectively single-platform .NET languages and Java. – Matt Joiner Feb 21 '10 at 22:03
2
int main();
int main(int argc, char* argv[]);

These are standard C++.

int _tmain(int argc, _TCHAR* argv[]);
int wmain(int argc, wchar_t* argv[]);

These are Windows-specific to handle Unicode arguments. See What is the difference between _tmain() and main() in C++?.

int main(array<System::String^>^ args);

This is not C++. This is C++/CLI.

For best portability, always use the first form.


Also,

int main(int argc, char** argv, char** envp);

This is a usually seen POSIX extension. Windows supports this form of main too. The envp means (pointer to) environment variables.

int main(int argc, char** argv, char** envp, char** apple);

This is for Mac only, obviously.

void main();

And this is wrong (nonstandard, some compilers (e.g. gcc) will reject it).

Community
  • 1
  • 1
kennytm
  • 510,854
  • 105
  • 1,084
  • 1,005
  • `void main()` is accepted by some compilers as a non-standard extension. So, you missed a spot! –  Feb 21 '10 at 08:11
  • 1
    @STingRaySC: It works everywhere but it is wrong. http://homepages.tesco.net/J.deBoynePollard/FGA/legality-of-void-main.html – kennytm Feb 21 '10 at 08:15
  • From your link: *So if one's compiler's documentation happens to say anywhere that main may have the return type void then main may indeed have the return type void and a program with void main() is a conforming program.* What exactly is "wrong" about this? It's no more "wrong" than MS defining `wmain` as an entry point! –  Feb 21 '10 at 08:19
  • 1
    @STingRaySC: (1) I didn't say `wmain` is right. (2) And `gcc` complains `error: ‘::main’ must return ‘int’`. – kennytm Feb 21 '10 at 08:24
2

Visual C++ Express will compile the first example just fine. However, you need to ensure the proper project settings:

  1. Create an "Empty Project"
  2. "Add a new item..." to the project via the "Project" menu. Select C++ (.cpp) file.
  3. Copy/Paste code into new file
  4. Press F5 to compile and run.
  5. When "Project is out of date" dialog appears, press "Yes" (build the project)

The steps above ensure VC++ Express does not treat your file as a special Win32/Windows console application.

EDIT: added additional step 5 to prevent "Can't find..." dialog. I managed to get the same dialog by making sure the exe file does not exist, and answering "No" to the build dialog. With a clean, empty project the exe file does not exist yet. It must be built first. If you answer "no" don't build it, VC++ dutifully does not build the exe and later complains about not being able to find it when it tries to run it later.

Leftium
  • 16,497
  • 6
  • 64
  • 99
  • I will try that out but here is the thing. If you look at the second image in my question. it says it can't find debug/www.exe . When I look into the folder, I do not see the executable file. Is one suppose to be created at compile time ?? if so, why isnt it there ? – numerical25 Feb 21 '10 at 20:21
  • I have added an extra step that I usually skip (my settings automatically build.) Please note I have gotten your exact code to compile using my steps, and I have also reproduced your "Cannot find..." dialog. – Leftium Feb 21 '10 at 21:12
  • @numerical25: to answer your question, yes the "www.exe" is the executable file and it should be created when you build. If it is not, then the build is failing for some reason. Can you tell us what shows up in the "output" window when you try to build? –  Feb 21 '10 at 21:50
  • I figured it out. I just posted my solution as a answer. I got to give it to peter. Even though I figure it out myself, He came closest to the solution. i appreciate your patients and your help – numerical25 Feb 21 '10 at 22:16
  • I wish I could change the title of this post so people understand the real issue – numerical25 Feb 21 '10 at 22:23
1

As STingRaySC pointed out, all three of your examples will compile in VC2008 express; it's just that examples 2 and 3 are what VC2008 Express will load up initially when you create a project (one of the examples is for Managed C++, as STingRaySC mentioned).

You can just delete the code in your second example (the C++ Win32 Console Application project) and paste in the more standard hello world program from your first example. It should compile and run just fine in VC2008 Express - it did for me.

Community
  • 1
  • 1
Michael Burr
  • 333,147
  • 50
  • 533
  • 760
1

I. Precompiled header

#include "stdafx.h"

is some kind of tricky stuff that comes your way. If you create a project VC will normally switch on precompiled header. This means that one header stdafx.h is created which is compiled only once. This is done to speed up compile time in big environments. If you start C++ it will confuse you. If you use stdafx.h it has to be the first header in the cpp file.

II. Unicode (Utf16)

int _tmain(int argc, _TCHAR* argv[])

Microsoft uses UTF16 to implement unicode strings. This means you get two versions of main.

int main(int argc, char* argv[])
int main(int argc, wchar_t* argv[])

This is also confusing if you start.

To simply start you can use whatever editor you want. Create the file. Open a Visdual studio 2008 command prompt

cl main.cpp
main.exe

and you will see Hello World using code from books. Afterwards try to understand some of the settings of VC.

But you should always use an empty project. Else you have to care about stdafx, UNICODE, ...

Totonga
  • 4,236
  • 2
  • 25
  • 31
0

_tmain with the _TCHAR argv is the way the C runtime allows you to handle unicode. If _UNICODE is defined, then _tmain will expand to wmain, and the _TCHAR argument will be of type wchar_t. If _UNICODE is not defined, then _tmain will expand to main, which will be the ANSI standard.

Therefore, so long as _UNICODE is not defined, the second snippet you posted is compliant with the standard.

Billy ONeal
  • 104,103
  • 58
  • 317
  • 552
  • Thanks for the response but that wasnt I was asking. What I posted was 3 versions of a console application. I am trying to distinguish the 3. – numerical25 Feb 21 '10 at 05:51
  • Then the first two are both valid C++ which will compile just fine, the last one is a C++/CLR application. – Billy ONeal Feb 21 '10 at 05:52
  • If that is the case, STingRaySC's answer is the one you're looking for. – Billy ONeal Feb 21 '10 at 05:53
  • I see that. his response came after this initial post. But how do i compile the first snippet in express 2008. – numerical25 Feb 21 '10 at 06:15
  • Put it in a .cpp file and point the IDE at it. Just because the "create a project" wizard fills in some default code for you doesn't mean you MUST use that code ;) – Billy ONeal Feb 21 '10 at 06:18
0

Lots of waxing lyrical and some misinformation for you sift through already, but I suggest following wonsungi's advice. But to clarify his advice:

  1. File->New->Project
  2. Select Project Type "Win32", then Template "Win32 Console Project"
  3. Give the project a name and location
  4. OK
  5. Select "Application Settings"
  6. Check "Empty Project"
  7. In the "Solution Explorer", right click the "Sources" folder, then Add->New Item
  8. Type the name of the file, in the "name" box using a .cpp extension (you can ignore the templates if you wish).
  9. Enter your code in the new file.
Clifford
  • 88,407
  • 13
  • 85
  • 165
0

Woot!! I figured it out!!! Below is my original code

#include <iostream>
int main(  )
{
    std::cout << "Hello World\n";
    return (0);
}

It was missing the header file #include "stdafx.h" . So I had to include it in there so I added it like this

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

int main(  )
{
    std::cout << "Hello World\n";
    return (0);
}

I was still getting an error like what you see in my edited question at the bottom. So What I did is I took #include and added it in my header file and then it worked!!!!!

Even the the books and alot of tutorials show to add #include to the actual cpp, for some reason in express edition I had to add it to header for it to work. I don't know WHY but it's a solution and now it works.

numerical25
  • 10,524
  • 36
  • 130
  • 209
-1

Download and install Dev-C++ on your system. If the code doesn't work on Visual C++, try it out on Dev-C++ (which uses the GCC compiler). You may get the same results or a different error message. Whenever you get an error message you don't understand, do a Internet search for the error message.

C.D. Reimer
  • 115
  • 11
  • 1
    -1: Doesn't answer the question. Furthermore, only the first snippet will build on a non-MS implementation. The OP is already trying to use VS -- he doesn't need to take on another development environment just to compile "hello world." –  Feb 21 '10 at 06:16
  • My post was aimed at the title, "getting the right compiler for C++", rather than the confusing question (if there was one). – C.D. Reimer Feb 21 '10 at 06:18
  • 1
    Fair enough, but that's not his/her problem. (S)He has a perfectly good C++ compiler. –  Feb 21 '10 at 06:19
  • 1
    I help out regularly on the Dev-C++ forum on sourceforge, and even I no longer recommend Dev-C++ to anyone over VC++ Express. I don't even install Dev-C++ any longer, its whole raison d'etre has gone, and its debugger integration sucks. – Clifford Feb 21 '10 at 08:48
  • 2
    CodeBlocks is probably a better alternative than Dev-C++ for those who don't want to use VC++. – Manuel Feb 21 '10 at 09:21
  • 3
    Yes, tell the poor newbie to install a buggy piece of junk that hasn't been supported for 5 years. WHY? Do you really hate beginning C++ developers so much? – jalf Feb 21 '10 at 14:44
  • Thanks for the recommendation of CodeBlocks. I wasn't aware of it. As for Dev-C++, I did learn C++ on that IDE five years ago since my instructor couldn't figure out how to use the newest version of Visual Studio. (He was a Unix guy.) Sorry I made the mistake of trying to answer a very confusing question. Excuse me while I go back to Vi to finish my program. :P – C.D. Reimer Feb 21 '10 at 20:38