Solved

"using namespace std;" doesn't work in Visual Studio 2008 for outputting to file

Posted on 2011-09-07
16
909 Views
Last Modified: 2012-08-14
I was trying to compile the following program I found on the Internet::

#include <fstream>
#include <iostream>

int main()
{
    using namespace std;

    // ofstream is used for writing files
    // We'll make a file called Sample.dat
    ofstream outf("Sample.dat");

    // If we couldn't open the output file stream for writing
    if (!outf)
    {
        // Print an error and exit
        cerr << "Uh oh, Sample.dat could not be opened for writing!" << endl;
        exit(1);
    }

    // We'll write two lines into this file
    outf << "This is line 1" << endl;
    outf << "This is line 2" << endl;

    return 0;

    // When outf goes out of scope, the ofstream
    // destructor will close the file
}

Open in new window


And Visual Studio spit out some strange error at me:

CS106CPPLib.lib(genlib.obj) : error LNK2019: unresolved external symbol "int __cdecl Main(void)" (?Main@@YAHXZ) referenced in function "int __cdecl mainWrapper(void)" (?mainWrapper@@YAHXZ)

I then decided to remove "using namespace std;" and received some of the following errors instead:

error C2065: 'ofstream' : undeclared identifier
error C3861: 'outf': identifier not found
error C2065: 'cerr' : undeclared identifier
error C2065: 'endl' : undeclared identifier

It wasn't till I completely removed "using namespace std;" and instead used "simpio.h" (one of the libraries provided with an online class I found) that I solved the problem.

How can I use these different functions without including "simpio.h". I want to learn to do it the same way everyone else does it in Visual Studio rather than using libraries that are only used in a single course.
0
Comment
Question by:Eindoofus
  • 8
  • 7
16 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 500 total points
ID: 36497399
You should either use
#include <fstream>
#include <iostream>
using namespace std; // <-- place it here

int main()
{
    
    // ofstream is used for writing files
    // We'll make a file called Sample.dat
    ofstream outf("Sample.dat");

    // If we couldn't open the output file stream for writing
    if (!outf)
    {
        // Print an error and exit
        cerr << "Uh oh, Sample.dat could not be opened for writing!" << endl;
        exit(1);
    }

    // We'll write two lines into this file
    outf << "This is line 1" << endl;
    outf << "This is line 2" << endl;

    return 0;

    // When outf goes out of scope, the ofstream
    // destructor will close the file
}

Open in new window


or refer to the symbols explicitly as
#include <fstream>
#include <iostream>

int main()
{
    // ofstream is used for writing files
    // We'll make a file called Sample.dat
    std::ofstream outf("Sample.dat");

    // If we couldn't open the output file stream for writing
    if (!outf)
    {
        // Print an error and exit
        std::cerr << "Uh oh, Sample.dat could not be opened for writing!" << std::endl;
        exit(1);
    }

    // We'll write two lines into this file
    outf << "This is line 1" << std::endl;
    outf << "This is line 2" << std::endl;

    return 0;

    // When outf goes out of scope, the ofstream
    // destructor will close the file
}

Open in new window

0
 

Author Comment

by:Eindoofus
ID: 36497453
Thanks @jkr, but placing the "using namespace std;" just gives me the following error:

CS106CPPLib.lib(genlib.obj) : error LNK2019: unresolved external symbol "int __cdecl Main(void)" (?Main@@YAHXZ) referenced in function "int __cdecl mainWrapper(void)" (?mainWrapper@@YAHXZ)
Debug\CS106B Blank Project.exe : fatal error LNK1120: 1 unresolved externals

and the second with "std::" gives me:

CS106CPPLib.lib(genlib.obj) : error LNK2019: unresolved external symbol "int __cdecl Main(void)" (?Main@@YAHXZ) referenced in function "int __cdecl mainWrapper(void)" (?mainWrapper@@YAHXZ)
Debug\CS106B Blank Project.exe : fatal error LNK1120: 1 unresolved externals
0
 
LVL 86

Expert Comment

by:jkr
ID: 36497484
Hm, these are linker errors - actually weird ones. What happens if you go to 'Tools|Visual C++ 2008 Command Prompt, 'cd' to the directory where your source file lives and then type

cl.exe myfile.cpp

?
0
 

Author Comment

by:Eindoofus
ID: 36497497
It worked after I created an empty project from scratch. What settings could be set wrong in the course's blank project solution to prevent this from compiling?
0
 

Author Comment

by:Eindoofus
ID: 36497552
When I run "cl.exe main.cc" on the file in the course's blank project directory I get the following:

C:\Documents and Settings\user1\My Documents\CS106B\WritingFiles>cl.exe main.cc
Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.30729.01 for 80x86
Copyright (C) Microsoft Corporation.  All rights reserved.

main.cc
C:\Program Files\Microsoft Visual Studio 9.0\VC\INCLUDE\xlocale(342) : warning C
4530: C++ exception handler used, but unwind semantics are not enabled. Specify
/EHsc
Microsoft (R) Incremental Linker Version 9.00.30729.01
Copyright (C) Microsoft Corporation.  All rights reserved.

/out:main.exe
main.obj

Open in new window


And main.exe creates Sample.dat, so everything appears to work fine.

But when I try to compile it in Visual Studio 2008 I get:

Linking...
CS106CPPLib.lib(genlib.obj) : error LNK2019: unresolved external symbol "int __cdecl Main(void)" (?Main@@YAHXZ) referenced in function "int __cdecl mainWrapper(void)" (?mainWrapper@@YAHXZ)
Debug\CS106B Blank Project.exe : fatal error LNK1120: 1 unresolved externals
Build log was saved at "file://c:\Documents and Settings\user1\My Documents\CS106B\WritingFiles\Debug\BuildLog.htm"
CS106B Blank Project - 2 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Open in new window


I got the blank project from:

http://www.stanford.edu/class/cs106b/materials/blank-pc-project.zip
0
 
LVL 86

Expert Comment

by:jkr
ID: 36497591
Well, it should be a lowercase 'main()', so I am quite puzzled. You did select a "Win32 Console Project", didn't you?
0
 

Author Comment

by:Eindoofus
ID: 36497856
No, when it worked in Visual Studio 2008 I had created an empty project and added a cpp file to it. However, when I use:

http://www.stanford.edu/class/cs106b/materials/blank-pc-project.zip

and edit it's contents I still get an error. That class blank pc project only works when I omit "using namespace std;" and include "simpio.h" (which is a custom library for the class). However, the class blank project still compiles when I use your "cl.exe main.cc" with the "using namespace std;".
0
 
LVL 86

Expert Comment

by:jkr
ID: 36497872
Can you post your linker settings? You'll find them under "Project Properties|C/C++|Linker|Advanced".
0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 

Author Comment

by:Eindoofus
ID: 36497926
0
 
LVL 86

Expert Comment

by:jkr
ID: 36498036
Sorry, my fault - the text content of 'Command Line' would be a lot more helpful.
0
 

Author Comment

by:Eindoofus
ID: 36500104
0
 
LVL 44

Expert Comment

by:AndyAinscow
ID: 36500864
>>CS106CPPLib.lib(genlib.obj) : error LNK2019: unresolved external symbol "int __cdecl Main(void)" (?Main@@YAHXZ) referenced in function "int __cdecl mainWrapper(void)" (?mainWrapper@@YAHXZ)


Maybe not relevant but a quick search (MSDN) on mainWrapper finds lots of hits for java and ASP.
0
 
LVL 86

Expert Comment

by:jkr
ID: 36503866
Hmmmm.... maybe as a last resort - could you post your .vcproj file (just open it with a text editor and copy the contents)?
0
 

Author Comment

by:Eindoofus
ID: 36508177
#include <fstream>
#include <iostream>
using namespace std; // <-- place it here

int main()
{
    
    // ofstream is used for writing files
    // We'll make a file called Sample.dat
    ofstream outf("Sample.dat");

    // If we couldn't open the output file stream for writing
    if (!outf)
    {
        // Print an error and exit
        cerr << "Uh oh, Sample.dat could not be opened for writing!" << endl;
        exit(1);
    }

    // We'll write two lines into this file
    outf << "This is line 1" << endl;
    outf << "This is line 2" << endl;

    return 0;

    // When outf goes out of scope, the ofstream
    // destructor will close the file
}

Open in new window


<?xml version="1.0" encoding="Windows-1252"?>
<VisualStudioProject
	ProjectType="Visual C++"
	Version="9.00"
	Name="CS106B Blank Project"
	ProjectGUID="{F30AA0EB-1D02-4964-8CF6-810AAAE6A9B4}"
	RootNamespace="Boggle"
	TargetFrameworkVersion="131072"
	>
	<Platforms>
		<Platform
			Name="Win32"
		/>
	</Platforms>
	<ToolFiles>
	</ToolFiles>
	<Configurations>
		<Configuration
			Name="Debug|Win32"
			OutputDirectory="$(ConfigurationName)"
			IntermediateDirectory="$(ConfigurationName)"
			ConfigurationType="1"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
				Optimization="0"
				AdditionalIncludeDirectories=".\cs106"
				RuntimeLibrary="1"
				DefaultCharIsUnsigned="true"
				WarningLevel="2"
				SuppressStartupBanner="true"
				DebugInformationFormat="4"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				AdditionalDependencies=".\cs106\CS106CPPLib.lib winmm.lib"
				SuppressStartupBanner="true"
				IgnoreDefaultLibraryNames="libc.lib; libcd.lib"
				GenerateDebugInformation="true"
				SubSystem="2"
				RandomizedBaseAddress="1"
				DataExecutionPrevention="0"
				TargetMachine="1"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
			/>
		</Configuration>
		<Configuration
			Name="Release|Win32"
			OutputDirectory="$(ConfigurationName)"
			IntermediateDirectory="$(ConfigurationName)"
			ConfigurationType="1"
			>
			<Tool
				Name="VCPreBuildEventTool"
			/>
			<Tool
				Name="VCCustomBuildTool"
			/>
			<Tool
				Name="VCXMLDataGeneratorTool"
			/>
			<Tool
				Name="VCWebServiceProxyGeneratorTool"
			/>
			<Tool
				Name="VCMIDLTool"
			/>
			<Tool
				Name="VCCLCompilerTool"
			/>
			<Tool
				Name="VCManagedResourceCompilerTool"
			/>
			<Tool
				Name="VCResourceCompilerTool"
			/>
			<Tool
				Name="VCPreLinkEventTool"
			/>
			<Tool
				Name="VCLinkerTool"
				RandomizedBaseAddress="1"
				DataExecutionPrevention="0"
			/>
			<Tool
				Name="VCALinkTool"
			/>
			<Tool
				Name="VCManifestTool"
			/>
			<Tool
				Name="VCXDCMakeTool"
			/>
			<Tool
				Name="VCBscMakeTool"
			/>
			<Tool
				Name="VCFxCopTool"
			/>
			<Tool
				Name="VCAppVerifierTool"
			/>
			<Tool
				Name="VCPostBuildEventTool"
			/>
		</Configuration>
	</Configurations>
	<References>
	</References>
	<Files>
		<Filter
			Name="Source Files"
			Filter="txt"
			>
			<File
				RelativePath=".\main.cc"
				>
			</File>
		</Filter>
	</Files>
	<Globals>
	</Globals>
</VisualStudioProject>

Open in new window

0
 
LVL 86

Expert Comment

by:jkr
ID: 36510918
Hmm, there's just one thing that I find weird, which is

IgnoreDefaultLibraryNames="libc.lib; libcd.lib"

Can you try to remove these from 'Configuration Properties|Linker|Input'?
0
 

Author Comment

by:Eindoofus
ID: 36512588
Unfortunately that didn't work. I'm still getting:

Linking...
CS106CPPLib.lib(genlib.obj) : error LNK2019: unresolved external symbol "int __cdecl Main(void)" (?Main@@YAHXZ) referenced in function "int __cdecl mainWrapper(void)" (?mainWrapper@@YAHXZ)
Debug\CS106B Blank Project.exe : fatal error LNK1120: 1 unresolved externals
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

The following diagram presents a diamond class hierarchy: As depicted, diamond inheritance denotes when two classes (e.g., CDerived1 and CDerived2), separately extending a common base class (e.g., CBase), are sub classed simultaneously by a fourt…
In Easy String Encryption Using CryptoAPI in C++ (http://www.experts-exchange.com/viewArticle.jsp?aid=1193) I described how to encrypt text and recommended that the encrypted text be stored as a series of hexadecimal digits -- because cyphertext may…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.
The viewer will learn how to user default arguments when defining functions. This method of defining functions will be contrasted with the non-default-argument of defining functions.

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

12 Experts available now in Live!

Get 1:1 Help Now