tags:

views:

514

answers:

12

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.

alt text

alt text [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.

+18  A: 

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.
Wow! An answer that's actually correct! That seems to be rare on this question.
Billy ONeal
Thanks. I humbly accept your *upvote* (please). :)
Already done. Your answer has a 1 next to it, no? :)
Billy ONeal
Unless something horribly exploded, or likely an option isn't set correctly, they'd work. +1
Xorlev
@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
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
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
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
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
A: 

_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
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
Then the first two are both valid C++ which will compile just fine, the last one is a C++/CLR application.
Billy ONeal
If that is the case, STingRaySC's answer is the one you're looking for.
Billy ONeal
I see that. his response came after this initial post. But how do i compile the first snippet in express 2008.
numerical25
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
A: 

If you compile the first one. It does not work. And alot of tutorials online start with the first one. I some what figure it out. I was able to find this

http://msdn.microsoft.com/en-us/library/ms235639%28VS.80%29.aspx

Apparently the first snippet of code is considered to be native c++ language. And the only way (or atleast the only way I could ) get it to work is to run it through the command line. By first turning it into a executable and then running.

I am guessing that the first one (native c++) is Purely procedural language where as the second ones (the newer ones) are procedural but also can implement the .Net framework and also use classes and namespaces.

I remember along time ago you could run the native language in the IDE. but since microsoft is completely moving away from DOS and is moving towards a newer system, it isn't as easy as it use to be compile a native c++ code.

I am only making assumptions. correct me if I am wrong.

numerical25
Again, the user already has a native code snippet. EDIT: Also.. answering with a guess doesn't seem like it helps all that much.
Billy ONeal
I know, that is what I was trying to figure out. What was the difference between the native code and the other 2. The native code does not compile correctly in a newer IDE and I was trying to figure out why. the link shows how to get it to work.
numerical25
Almost everything about what you said is wrong. Next time, edit your question to clarify what you know and what you are looking for. Don't post an answer seeking more information (it'll get downvoted till the cows come home).
well apparently you know the answer.
numerical25
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)!
well I figured out how to build the second 2. But I am not sure how to build the first 1. atleast the only way I have figured out was through the link i provided
numerical25
What is the problem when trying to build the first one?
It says it can't find compiler definitions. But to think about it. It might be something wrong with the IDE itself. It just threw me off because the last 2 snippets worked fine and they are also the initial code. but when I added the first one which is not the initial code I got a error which did not come from the debug window. I will probably try to reinstall the application. It is also saying for all my projects that they are out of date which is also strange.
numerical25
You can't have multiple .cpp files in the same project that define `main` (or `_tmain`). Not sure if this might be the source of your error. The "out of date..." dialog is because you are changing something and trying to run without rebuilding. It's unlikely that your IDE is somehow corrupted. If you are using the right type of project (Win32 Console App, among others that will work), the first snippet **will** build! Can you be more specific than "it can't find compiler definitions?"
I understand. I updated my question to show what happens when build the first snippet code. And yes I do save it before I build. hopefully that will help? I appreciate the efforts by the way.
numerical25
A: 

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
-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."
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
Fair enough, but that's not his/her problem. (S)He has a perfectly good C++ compiler.
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
CodeBlocks is probably a better alternative than Dev-C++ for those who don't want to use VC++.
Manuel
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
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
+1  A: 

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.

Michael Burr
+2  A: 
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 http://stackoverflow.com/questions/895827/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).

KennyTM
`void main()` is accepted by some compilers as a non-standard extension. So, you missed a spot!
@STingRaySC: It works everywhere but it is wrong. http://homepages.tesco.net/J.deBoynePollard/FGA/legality-of-void-main.html
KennyTM
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!
@STingRaySC: (1) I didn't say `wmain` is right. (2) And `gcc` complains `error: ‘::main’ must return ‘int’`.
KennyTM
I'm bored now...
+2  A: 

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
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
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
@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?
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
I wish I could change the title of this post so people understand the real issue
numerical25
+4  A: 

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
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
The last One is C++/CLI which is a new language by itselg, however close to C++.
kriss
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
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
-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.
This answer is nothing like C.D Reimer's answer. I'm sorry your planetary immigration was denied, join us sometime.
Matt Joiner
@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.
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
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
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
A: 

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
+1  A: 

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
you were right to include #include "stdafx.h"
numerical25
+6  A: 

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
I didn't see your answer before I figured it out but you came the closest to what was wrong.
numerical25
also that is a very useful tip to turn off precompiled headers
numerical25
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. :)
The quick and the dead... I'll give you an upvote for a consolation prize though ;-)
Peter
A: 

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