?
Solved

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

Posted on 2011-09-07
16
Medium Priority
?
1,049 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 8
  • 7
16 Comments
 
LVL 86

Accepted Solution

by:
jkr earned 2000 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
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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
 

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
 
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

Free Tool: Port Scanner

Check which ports are open to the outside world. Helps make sure that your firewall rules are working as intended.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
Introduction This article is a continuation of the C/C++ Visual Studio Express debugger series. Part 1 provided a quick start guide in using the debugger. Part 2 focused on additional topics in breakpoints. As your assignments become a little more …
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will be introduced to the technique of using vectors in C++. The video will cover how to define a vector, store values in the vector and retrieve data from the values stored in the vector.
Suggested Courses

777 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