Register a SA Forums Account here!
JOINING THE SA FORUMS WILL REMOVE THIS BIG AD, THE ANNOYING UNDERLINED ADS, AND STUPID INTERSTITIAL ADS!!!

You can: log in, read the tech support FAQ, or request your lost password. This dumb message (and those ads) will appear on every screen until you register! Get rid of this crap by registering your own SA Forums Account and joining roughly 150,000 Goons, for the one-time price of $9.95! We charge money because it costs us money per month for bills, and since we don't believe in showing ads to our users, we try to make the money back through forum registrations.
 
  • Post
  • Reply
fret logic
Mar 8, 2005
roffle
Is the Ansi C Programming Language a good book to learn C from if you're familiar with the basics of programming, or are there better books to start with?

Adbot
ADBOT LOVES YOU

Professor Science
Mar 8, 2006
diplodocus + mortarboard = party

fret logic posted:

Is the Ansi C Programming Language a good book to learn C from if you're familiar with the basics of programming, or are there better books to start with?
is this Kernighan and Ritchie? K&R is *the* book

fret logic
Mar 8, 2005
roffle

Professor Science posted:

is this Kernighan and Ritchie? K&R is *the* book

Yes, but is the one I'm talking about the right one? I know the K&R "style" is supposed to come from the first edition, and that the second one is the ansi style. Should I be using the first or second edition?

Professor Science
Mar 8, 2006
diplodocus + mortarboard = party

fret logic posted:

Yes, but is the one I'm talking about the right one? I know the K&R "style" is supposed to come from the first edition, and that the second one is the ansi style. Should I be using the first or second edition?
absolutely use the second edition

fret logic
Mar 8, 2005
roffle

Professor Science posted:

absolutely use the second edition

Alright thanks :)

sd6
Jan 14, 2008

This has all been posted before, and it will all be posted again
I just started learning a little bit of C in one of my classes, and it's really interesting. I want to learn more of it and eventually maybe start learning C++ after. I totally intend to get the K & R book eventually, but I'm completely broke right now. Is there a really good online C resource for beginners that I can use in the mean time?

freddy-10eighty
Apr 3, 2007
I'm currently taking an intro to C++ at my uni.... can anyone tell me how to compile and run C++ files on a mac? I've tried using XCode, and it's a bit overwhelming since I'm still new to this...basically, when I write code, compile and build in MS Visual studio, a console window pops up and allows me to test out my program, but the same thing doesnt happen with XCode...nothing pops up.

Allie
Jan 17, 2004

freddy-10eighty posted:

I'm currently taking an intro to C++ at my uni.... can anyone tell me how to compile and run C++ files on a mac? I've tried using XCode, and it's a bit overwhelming since I'm still new to this...basically, when I write code, compile and build in MS Visual studio, a console window pops up and allows me to test out my program, but the same thing doesnt happen with XCode...nothing pops up.

Open up Terminal.app (in /Applications/Utilities) and use g++ to compile your application. Much simpler than dealing with a huge IDE and hundreds of project settings.

And don't forget the -Wall -Wextra switches. :)

Ari
Jun 18, 2002

Ask me about who Jewish girls should not marry!
GCC's not linking in certain libraries in the C standard library. I can't find any documentation anywhere to help me figure out how to link these in, or force GCC to always link whatever's necessary - any ideas?

New Debian installation, GCC 4.1.2.

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Ari posted:

GCC's not linking in certain libraries in the C standard library. I can't find any documentation anywhere to help me figure out how to link these in, or force GCC to always link whatever's necessary - any ideas?

New Debian installation, GCC 4.1.2.

The standard library is only a single library, libc, which is always linked in unless you explicitly specify not to. What error are you getting?

Ari
Jun 18, 2002

Ask me about who Jewish girls should not marry!

ShoulderDaemon posted:

The standard library is only a single library, libc, which is always linked in unless you explicitly specify not to. What error are you getting?

code:
ari@beren:~/cs$ cat thing.c
#include <stdio.h>
#include <math.h>

int main()
{
        double x = 4.0;
        printf("%f\n",sqrt(x));
        return 0;
}
ari@beren:~/cs$ gcc -o thing thing.c
/tmp/cceWZZcu.o: In function `main':
thing.c:(.text+0x35): undefined reference to `sqrt'
collect2: ld returned 1 exit status
ari@beren:~/cs$
This happens whenever I need to reference a function from math.h or stdlib.h - I just gave an example here from math.h. The stdio functions work fine though.

floWenoL
Oct 23, 2002

Ari posted:

This happens whenever I need to reference a function from math.h or stdlib.h - I just gave an example here from math.h. The stdio functions work fine though.

Try "-lm".

FigBug
Apr 27, 2002

Lemon Party - Lest we Forget

Ari posted:

This happens whenever I need to reference a function from math.h or stdlib.h - I just gave an example here from math.h. The stdio functions work fine though.

Add -lmath

ShoulderDaemon
Oct 9, 2003
support goon fund
Taco Defender

Ari posted:

code:
ari@beren:~/cs$ cat thing.c
#include <stdio.h>
#include <math.h>

int main()
{
        double x = 4.0;
        printf("%f\n",sqrt(x));
        return 0;
}
ari@beren:~/cs$ gcc -o thing thing.c
/tmp/cceWZZcu.o: In function `main':
thing.c:(.text+0x35): undefined reference to `sqrt'
collect2: ld returned 1 exit status
ari@beren:~/cs$
This happens whenever I need to reference a function from math.h or stdlib.h - I just gave an example here from math.h. The stdio functions work fine though.

You can add -lm to the end of the gcc command, which will link in the math library, or if you're on x86 you can add -O which turns on optimizations, including transforming sqrt calls to direct FPU invocation, removing the need for the math library.

In the manpage for sqrt(3) you may note the line "Link with -lm.", which specifies which library the function is defined in. Another way to find symbols is "nm -A --defined-only /usr/lib/*.a 2>/dev/null | grep sqrt", which will list all the symbols in all the development libraries you have installed, and search for those that match "sqrt". If a library is called "/usr/lib/libm.a", then you link to it by adding "-lm" at the end of the gcc line.

Doc Block
Apr 15, 2003
Fun Shoe

freddy-10eighty posted:

I'm currently taking an intro to C++ at my uni.... can anyone tell me how to compile and run C++ files on a mac? I've tried using XCode, and it's a bit overwhelming since I'm still new to this...basically, when I write code, compile and build in MS Visual studio, a console window pops up and allows me to test out my program, but the same thing doesnt happen with XCode...nothing pops up.

It's a difference between the way Windows and Unix systems (including OS X) work when it comes to command-line vs GUI apps.

If you want to see your program's output, open up Terminal.app (it's in /Applications/Utilities), cd to yourprojectdir/build/(Release or Debug)/yourproject.app/Contents/MacOS and then type ./yourproject to run it.

Or, for simple little CLI programs don't bother with a big IDE like Xcode and just run g++ from the command-line.

Doc Block fucked around with this message at 11:29 on Feb 21, 2008

Ari
Jun 18, 2002

Ask me about who Jewish girls should not marry!

ShoulderDaemon posted:

You can add -lm to the end of the gcc command, which will link in the math library, or if you're on x86 you can add -O which turns on optimizations, including transforming sqrt calls to direct FPU invocation, removing the need for the math library.

In the manpage for sqrt(3) you may note the line "Link with -lm.", which specifies which library the function is defined in. Another way to find symbols is "nm -A --defined-only /usr/lib/*.a 2>/dev/null | grep sqrt", which will list all the symbols in all the development libraries you have installed, and search for those that match "sqrt". If a library is called "/usr/lib/libm.a", then you link to it by adding "-lm" at the end of the gcc line.

I bolded the lines that helped to answer my question, thanks. Someone had shown me the "-lm" to link in the math library a couple of days ago, but it didn't help for things that came from stdlib.h, for example the atof function. I didn't know how to find what library to link in to make sure I had coverage for all of my imported functions. Thanks for your help :D

Doc Block
Apr 15, 2003
Fun Shoe
If GCC can find stdlib.h but isn't linking in all the functions from the C standard library then something is wrong with your setup. You shouldn't need any extra command-line options to get the stuff in stdlib.h to work.

fret logic
Mar 8, 2005
roffle

Ari posted:

GCC's not linking in certain libraries in the C standard library. I can't find any documentation anywhere to help me figure out how to link these in, or force GCC to always link whatever's necessary - any ideas?

New Debian installation, GCC 4.1.2.

You may or may not have it, but "apt-get install build-essential" will solve a lot of problems. You probably already have it though if your compiler is working.

excitebike
May 18, 2003

kewlpc posted:

It's a difference between the way Windows and Unix systems (including OS X) work when it comes to command-line vs GUI apps.

If you want to see your program's output, open up Terminal.app (it's in /Applications/Utilities), cd to yourprojectdir/build/(Release or Debug)/yourproject.app/Contents/MacOS and then type ./yourproject to run it.

Or, for simple little CLI programs don't bother with a big IDE like Xcode and just run g++ from the command-line.

Optionally, since it seems like you are used to working with Visual Studio, and Xcode might be a more friendly environment until you are more comfortable working with the command line (which you should become at some point mind you)

stdout goes to Xcode's debug console, which can be access via Cmd-Shift-R. Running a C++ Tool that cout's some stuff will dump it into this window. You can also access it via Run->Console.

Lexical Unit
Sep 16, 2003

Let's say that now I want to make my container exception safe. I'm not sure where I can find information on what parts of the STL are exception safe (and at what level). If anyone can recommend a book or website that would help in this area please do. I have Sutter's Exceptional C++, just not on hand at the moment, so if that's good enough just let me know. I can go re-read it now that most of it isn't over my head.

In the mean time my immediate quandary involves conceptually reassuring myself that the following is no-throw guarantee exception safe:
code:
template< /* ... */ >
class trie
{
/* ... */
	private:
		typedef trie* trie_node;

		struct trie_node_delete
		{
			void operator()(trie_node const &node) throw()
			{
				delete node;
			}
		};

		struct trie_node_less { /* ... */ };
		typedef std::set<trie_node, trie_node_less> subtrie;

		subtrie children;
};

template< /* ... */ >
trie< /* ... */ >::~trie() throw()
{
	for_each (this->children.begin (), this->children.end (), trie_node_delete ());
}
What I'm unsure of is what exception guarantees does for_each(), begin(), end(), and other functions that those functions entail give me? Is this exception safe or not? If it is, do I have the no-throw guarantee?

more falafel please
Feb 26, 2005

forums poster

Lexical Unit posted:

Let's say that now I want to make my container exception safe. I'm not sure where I can find information on what parts of the STL are exception safe (and at what level). If anyone can recommend a book or website that would help in this area please do. I have Sutter's Exceptional C++, just not on hand at the moment, so if that's good enough just let me know. I can go re-read it now that most of it isn't over my head.

In the mean time my immediate quandary involves conceptually reassuring myself that the following is no-throw guarantee exception safe:
code:
template< /* ... */ >
class trie
{
/* ... */
	private:
		typedef trie* trie_node;

		struct trie_node_delete
		{
			void operator()(trie_node const &node) throw()
			{
				delete node;
			}
		};

		struct trie_node_less { /* ... */ };
		typedef std::set<trie_node, trie_node_less> subtrie;

		subtrie children;
};

template< /* ... */ >
trie< /* ... */ >::~trie() throw()
{
	for_each (this->children.begin (), this->children.end (), trie_node_delete ());
}
What I'm unsure of is what exception guarantees does for_each(), begin(), end(), and other functions that those functions entail give me? Is this exception safe or not? If it is, do I have the no-throw guarantee?

From the horse's mouth: http://www.research.att.com/~bs/3rd_safe.pdf

Lexical Unit
Sep 16, 2003

Beautiful.

Captain Frigate
Apr 30, 2007

you cant have it, you dont have nuff teef to chew it
I'm pretty new to C and I am wondering what the actual difference is between putchar/getchar and printf/scanf. Is there any?

Avenging Dentist
Oct 1, 2005

oh my god is that a circular saw that does not go in my mouth aaaaagh

Captain Frigate posted:

I'm pretty new to C and I am wondering what the actual difference is between putchar/getchar and printf/scanf. Is there any?

They are the exact opposites of each other. putchar and printf are for output, getchar and scanf are for input.

Captain Frigate
Apr 30, 2007

you cant have it, you dont have nuff teef to chew it

Avenging Dentist posted:

They are the exact opposites of each other. putchar and printf are for output, getchar and scanf are for input.

That's not quite what I meant. I meant are putchar and getchar (as a pair) functionally different from printf and scanf (as a pair)? What are the functional differences between the I/O pairs?

Doc Block
Apr 15, 2003
Fun Shoe
putchar and getchar only do one character at a time and don't do any format conversion.

For example:
code:
int answer;
printf("Type in the answer: ");
scanf("%d", &answer);
printf("You typed: %d\n", answer);

Doc Block fucked around with this message at 20:50 on Feb 22, 2008

Captain Frigate
Apr 30, 2007

you cant have it, you dont have nuff teef to chew it

kewlpc posted:

putchar and getchar only do one character at a time and don't do any format conversion.

For example:
code:
int answer;
printf("Type in the answer: ");
scanf("%d", &answer);
printf("You typed: %d\n", answer);

Cool, thanks

Space Duck
Oct 15, 2003
I haven't touched C++ in a couple of years, so maybe I'm just missing something obvious, but this has me stymied.

I have a class I'm using to log events from my app, imaginatively named Log.

What I'm trying to do is have a container class (QueueRunner) that monitors and trigger events from a queue, and log those events, failures, etc.

I have a constructor in QueueRunner that takes a Log object, and from there, I can write whatever I want to the log:
code:
QueueRunner::QueueRunner (const Log &logTarget){
	eventLog = logTarget;
	eventLog << "Queue runner started.";
 
}
eventLog is a private data member of type Log. That code produces the expected entry in the logfile.

Any subsequent member of the QueueRunner class seems unable to write to the log, however. This code segment doesn't do what I'd expect:
code:
void QueueRunner::StartListening (char *address, int port){
	
	eventLog << "Opening Listen socket...";
It's not writing to the log file, but I'm not getting errors or segfaults, either. I know that the copy constructor for Log works, but I still think there's something I've overlooked.

Edit: the Log object and the QueueRunner objects are both instantiated in main().

Vanadium
Jan 8, 2005

You are going to have to post some more code. Could you try reducing it to a testcase?

more falafel please
Feb 26, 2005

forums poster

Space Duck posted:

I haven't touched C++ in a couple of years, so maybe I'm just missing something obvious, but this has me stymied.

I have a class I'm using to log events from my app, imaginatively named Log.

What I'm trying to do is have a container class (QueueRunner) that monitors and trigger events from a queue, and log those events, failures, etc.

I have a constructor in QueueRunner that takes a Log object, and from there, I can write whatever I want to the log:
code:
QueueRunner::QueueRunner (const Log &logTarget){
	eventLog = logTarget;
	eventLog << "Queue runner started.";
 
}
eventLog is a private data member of type Log. That code produces the expected entry in the logfile.

Any subsequent member of the QueueRunner class seems unable to write to the log, however. This code segment doesn't do what I'd expect:
code:
void QueueRunner::StartListening (char *address, int port){
	
	eventLog << "Opening Listen socket...";
It's not writing to the log file, but I'm not getting errors or segfaults, either. I know that the copy constructor for Log works, but I still think there's something I've overlooked.

Edit: the Log object and the QueueRunner objects are both instantiated in main().

Is eventLog of type Log or Log&? If it's Log, does Log's assignment operator work normally, so that if one is copied, the copy has the same log file open?

Do you have one QueueRunner object or several?

Itaipava
Jun 24, 2007

more falafel please posted:

Is eventLog of type Log or Log&? If it's Log, does Log's assignment operator work normally, so that if one is copied, the copy has the same log file open?

I thought the same thing, but I don't think it can be Log&. If it were the case, wouldn't eventLog -have- to be assigned to log in the constructor's initialization list?

I'm leaning towards Log's assignment operator copying the file stream because of that signature (const Log &).

more falafel please
Feb 26, 2005

forums poster

Itaipava posted:

I thought the same thing, but I don't think it can be Log&. If it were the case, wouldn't eventLog -have- to be assigned to log in the constructor's initialization list?

I'm leaning towards Log's assignment operator copying the file stream because of that signature (const Log &).

Yeah, you're right about the reference assignment. He should be doing that anyway, though.

Space Duck
Oct 15, 2003
On Vandanium's suggestion, I've stubbed out a test case. I should have done that first, thanks for the suggestion. Now I'm suspecting that I've mangled something elsewhere, but have ideas of where to look next.

code:
testmain.cpp:
#include "TestClass.h"

using namespace std;

int main (void) {
	
	Log testLog ("testlog.txt");
	Log testLog2 (testLog);
	
	testLog << "This was called from Main.";
	testLog2 << "This should write to the same file as testLog";
	
	TestClass test (testLog);
	test.SomeOtherFunction();
	
	return 0;
}

TestClass.h:
#ifndef TESTCLASS_H
#define TESTCLASS_H
#include "qlib/Log.h"

using namespace std;

class TestClass {
private:
	Log eventLog;
public:
	TestClass (const Log &);
	void SomeOtherFunction (void);		
};

TestClass::TestClass (const Log &logTarget) {
	eventLog = logTarget;
	eventLog << "This was written from the TestClass constructor.";	
}

void TestClass::SomeOtherFunction () {
	eventLog << "This should be written to the log file as far as I know.";
}

#endif
That code does what I expected it to do, however. Here's the resulting file:
code:
# cat testlog.txt 
2008-02-22 16:52:51 This was called from Main.
2008-02-22 16:52:51 This should write to the same file as testLog
2008-02-22 16:52:51 This was written from the TestClass constructor.
2008-02-22 16:52:51 This should be written to the log file as far as I know.

quote:

Yeah, you're right about the reference assignment. He should be doing that anyway, though.

Yeah, I hit on that early on since streams aren't copyable.

JoeNotCharles
Mar 3, 2005

Yet beyond each tree there are only more trees.
Is your log class flushing the stream? If you're watching the log file in realtime, waiting for the lines to show up, they might just be buffered (which would happen too in your stubbed test case, except the program ends right after the last call which flushes all the buffers).

Itaipava
Jun 24, 2007
Does Log's destructor close the stream? I know you said the main Log is instantiated in main(), but is any Log object being destructed at all?

Ari
Jun 18, 2002

Ask me about who Jewish girls should not marry!

fret logic posted:

You may or may not have it, but "apt-get install build-essential" will solve a lot of problems. You probably already have it though if your compiler is working.

I didn't, and this fixed it entirely. Thanks :)

oldkike
Jan 10, 2003

hey

www.pleasegimmeadollar.com
I was trying to do a easy-to-use observer pattern in C++. I'm kind of new to it.

code:
#include <algorithm>
#include <functional>
#include <list>

using namespace std;

class Subject;

class Observer
{
   public:
      virtual void call(Subject *s) = 0;
};

template<class T>
class CbObserver : public Observer
{
public:
  CbObserver(void (T::*f)(Subject *), T *o) : mF(f), mO(o) {}
  void call(Subject *s) { ((mO).*(mF))(s); }
private:
  void (T::*mF)(Subject *);
  T* mO;
};

class Subject
{
public:
   void notify() {
      for(list<Observer *>::iterator i = mObservers.begin();
          i != mObservers.end();
          i++)
      {
          (*i)->call(this);
      }
   }
  void addObserver(Observer *o) { mObservers.push_back(o); }
private:
   list<Observer *> mObservers;
};

Is there any way to do this without having to do a "new" for every observer? Ideally I'd like for the Subject to be observed by multiple classes with multiple methods in each class..

Vanadium
Jan 8, 2005

Sure, just create all the observers on the stack or in an STL container.

Edit: Oops, I got that wrong. Nevermind what it said here before.

Vanadium fucked around with this message at 05:17 on Feb 25, 2008

fret logic
Mar 8, 2005
roffle

Ari posted:

I didn't, and this fixed it entirely. Thanks :)

Woohoo, I finally gave something back to CoC :)




Ok guys, I promise this is the last question I'm going to ask about learning before I put my head in a book for a while.

I'm learning C and C++ kind of at the same time. So far it's not a big deal since I'm able to differentiate pretty well between the two. I'm using "The C Programming Language" for C, and I just bought this for 7 bucks at a used bookstore:
http://www.amazon.com/Problem-Solving-C%2B%2B-Including-Laboratories/dp/0534400051/ref=sr_1_1?ie=UTF8&s=books&qid=1203928841&sr=1-1
I realize there are better books out there, so should I stick with this one or pick one up? The cost doesn't matter much to me, so if I can do a lot better with something else, I'd prefer to. Otherwise, I'll stick with this. What do you guys think?

Adbot
ADBOT LOVES YOU

Ari
Jun 18, 2002

Ask me about who Jewish girls should not marry!

fret logic posted:

I'm learning C and C++ kind of at the same time. So far it's not a big deal since I'm able to differentiate pretty well between the two. I'm using "The C Programming Language" for C, and I just bought this for 7 bucks at a used bookstore:
http://www.amazon.com/Problem-Solving-C%2B%2B-Including-Laboratories/dp/0534400051/ref=sr_1_1?ie=UTF8&s=books&qid=1203928841&sr=1-1
I realize there are better books out there, so should I stick with this one or pick one up? The cost doesn't matter much to me, so if I can do a lot better with something else, I'd prefer to. Otherwise, I'll stick with this. What do you guys think?

The question comes up pretty often as to the de facto library of books for learning various programming languages and concepts. In my experience reading threads discussing them and reading several of the books named, I think the general goon consensus is that Eckel's Thinking in C++ is the best one to pick up C++. But why are you learning both C and C++ at once?

  • 1
  • 2
  • 3
  • 4
  • 5
  • Post
  • Reply