You are not logged in.
The first programming language I learned was BASH (I know...) and then I moved on to Perl. I want to learn some C/C++ but I'm having trouble getting my head around it. Any suggestions?
Offline
Well it would be more helpful if you'd describe what produces problems for you, as from that three sentences one only can give you the link to another introduction, but doesn't know if it helps you.
Offline
@Atsutane: with respect to C/C++ I'm a complete newbie so it'd be nigh impossible for me to describe what I have trouble doing.
I tried writing a simple "hello world" in C++ and gcc just returned errors. I haven't the faintest idea what I'm doing wrong. I'm just looking for any tips/books to read for someone who is struggling with C++.
Should I learn C before learning C++?
Offline
Offline
I dont think its a good idea to learn C before using C++. That wont make it easier. Find a good book or tutorial to get started with the basics of the C++ syntax and the typesystem. Understand what the preprocessor and the compiler do (includes, preprocessor directives, translation units, linker). Try out what you learned and use reference material to clarify questions that come up.
Start with simple console programs that use only simple datatypes and easy to use functions (calculate something with integers and floats and print its results etc.). Learn how to use a debugger to see what your code is actually doing. Then read the some input from the console. Do your calculations with the read values and print them again. Then declare some simple structures and put the integers and floats in there. Learn how contructors and destructors work and use them to initialize and deinitialize instances of your stuctures. Understand pointers. Understand "new" and "delete" and how to use them correctly. Implement some methods for your structures. Write some more complex datastructures (at least a doubly linked list). Always use the debugger to see if the code does what you expect! Understand "const". Write some classes and understand what private/protected/public members are good for and how to use them. Move on to some reallife data structures: Use the STL to put your structures into std::vecor, std::list, std::map and other containers and do some more complex calculations. Understand iterators. Try out ineritance and virtual functions. And when you understood all parts of the language that you used so far: Write your linked list as template class so it can hold objects of any type.
I think starting early to debug your programs will help you a lot to understand what is going on. Then you dont have to guess what the program does: You can watch it and you will know fore sure what is going on. The debugger is your best friend. Watch your variables, see the callstack, set breakpoints to see when a line of code is executend and in what context it gets called.
And dont expect to learn C++ within a few weeks. The syntax is "complex" and the language has a lot of pitfalls. At the beginning you will have a lot of frustrating compiler errors. And when it compiles it will sometimes do things that you did not expected. But after you understood C++ and got exprecience in software development you will have learned a lot. Learning other languges like Java, C# will be a matter of a few days. They cant shock you when you know all pitfalls and tricks you have seen in C++
Offline
Well C++ was build up on C, but you don't need to learn C if you want to write your later code in C++ as nearly everything was replaced by the paradigmns of object orientation with classes and methods, so I can only say the same as g0ju, go to your library and get one or two books from there it'll help you more.
For your current problem: If you've checked that the base-devel group is installed and your source is correct, then compile C++ Code with g++ instead of gcc, as that's the C++ compiler, using gcc forces you to link the code against the C++ library.
Offline
I think many newbie C/C++-problems stem from a lack of understanding of the compilation process.
Compilation is broken into two main phases: Compiling and linking.
When compiling, your source code is transformed into so-called object code. Any syntax errors or type errors are caught during this phase. The result is an object file (whatever.o). This file can not be run as a program - it must be linked.
Linking produces a program or library from one or more object files. During this phase, use of external libraries (like libc) is resolved. You might get errors if a function you try to use, is not found, for example.
Now, let's walk through a very simple program step by step. This program probably have some weak points, I kinda made it up on the spot
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main(int argc, char** argv)
{
double deg, rad; /* a double is a way to work with fractional numbers on computers. It's not completely accurate, but it's relatively fast. The inaccuracies does usually not matter, unless you are working with rockets, medicine or finance. */
int i; /* we use this counter for our loop */
if(argc < 2) {
printf("Usage: %s [number] ...\n", argv[0]);
return 1; /* It's standard to return a number > 0 (often 1) on failure */
}
for(i = 1; i < argc; ++i) {
deg = atof(argv[i]);
if(deg != deg) { /* NaN, not a number, is not equal to itself */
printf("The %d. number was not valid\n", i);
continue; /* Go to next value of "i", skip the rest of this pass through the loop */
}
/* Let's convert the degrees into radians */
rad = deg * (M_PI / 180); /* The M_PI constant is defined in math.h */
rad = sin(rad);
/* and lets convert back into degrees */
rad = rad * (180 / M_PI);
printf("The sine of %f is %f\n", deg, rad);
}
return 0; /* It's standard to return 0 on success */
}
This idiotic little program can print the sines of a list of numbers.
First, copy the code into a file, and name it, for example, sine.c
Now, let's compile it:
$ gcc -c sine.c
Here, we ask GCC to compile (-c) the file sine.c.
This will produce an object file called sine.o
Now, let's create a program:
$ gcc -o sine sine.o
Here we ask gcc to output a file called sin (-o sine), from the object file sine.o
Ooops! This gives us the following error:
sin.o: In function `main':
sin.c:(.text+0x96): undefined reference to `sin'
collect2: ld returned 1 exit status
The function "sin", which we use, is not in any file we specify!
We use the math library (#include <math.h>), so we must tell gcc to link against the math library:
$ gcc -lm -o sine sine.o
The "-l" switch is used to tell gcc to link against a library. In this case, "-lm", the gcc linker looks for a file named "libm.so". So, to link against libfoo, I'll say "-lfoo".
Now we have a working program, which can be run like "./sine 180 270".
As you can see, I was kinda bored...
Offline
@Sternmull: thanks for the advice. I have some C++ books but I've never been able to get my head around them and they all use windows tools which really pisses me off. I think I'll find some tutorials online.
Offline
@gnud: very interesting. I think I understand things a bit better now. Thank you very much.
Offline
I bought "C++ Primer Plus" by Stephen Prata a while ago and if your serious about C/C++ i would hightly recommend you get it. Although some exposure to C would be helpful, it doesn't assume you have any prior knowledge. It takes you all the way thru programming in C/C++, starting with the compilation process, right up to the more advanced topics like OOP, Generics, Templates etc. etc.
Last edited by manx (2009-09-24 15:02:57)
Offline
C++ was the first programming language I learned and I did so from the great online book Thinking in C++ by Bruce Eckel. I found it very challenging but I learnt so much from that text. Worth a go, and it's free so there's nothing to lose but precious hours of your life!
Offline
May I suggest this book: http://www.amazon.com/Primer-Plus-5th-S … 0672326973
A really good one.
Birger
Offline
Obligatory: http://www.e-booksdirectory.com/programming.php#cpp
read, learn, love
Offline
Thanks again everyone. I'll follow those links and read up.
Offline
+1 for Thinking in C++
It requires some basic C knowledge, however.
Also really useful: C++ Annotations
To know or not to know ...
... the questions remain forever.
Offline
I bought "C++ Primer Plus" by Stephen Prata a while ago and if your serious about C/C++ i would hightly recommend you get it. Although some exposure to C would be helpful, it doesn't assume you have any prior knowledge. It takes you all the way thru programming in C/C++, starting with the compilation process, right up to the more advanced topics like OOP, Generics, Templates etc. etc.
Seconded on this, Stephen Prata is an excellent writer.
Offline
C++ was the first programming language I learned and I did so from the great online book Thinking in C++ by Bruce Eckel. I found it very challenging but I learnt so much from that text. Worth a go, and it's free so there's nothing to lose but precious hours of your life!
You mean that there are people who don't think in C? How do they get around the lack of linearity?
The best hello world c++ program is:
#include <iostream>
using namespace std;
int main(int argv, char *argc[])
{
char text[6] = "hello"; // Set 'text' to "hello\0"
cout << text << endl; // Print it out on the standard output, with and endline
return 0; // Provide the standard SUCCESS return value
}
Then (at the CLI) to compile:
$ g++ hello.cpp -o hello
$ ./hello
Exercise: Look up the main() arguments and make it accept input from the CLI!
Offline
@techprophet: you switched argc and argv.
Personally, I favor C, partly because my command of it is much greater than C++. But pick one and go with it; don't mix the two around. (Observe that gnud's listing was idiomatic C, whereas techprophet's is valid only in C++.) I think that hideous, unmaintainable code lies ahead of the programmer who writes C in C++ (or vice versa). This is not to say that one shouldn't learn both languages -- just that one should write idiomatic C++ when writing C++, and idiomatic C when writing C; things are so much easier to read that way. I would recommend a beginner to pick one and learn it well before moving on to the other.
Offline
I'm having a bit of trouble understanding the int main(int argc, char *argv[]) bit of the a typical C program
#include <stdio.h>
int main(int argc, char *argv[])
{
printf("Hello, you are learning C!!\n");
return 0;
}
That's a program I got from one of the books you guys recommended. It sort of explains it in the book but I'm still having some trouble understanding it. Just in case you guys were wondering, I've decided to learn C before I learn C++.
Offline
Argc is the arguments count, argv is the argument values, it's an array of pointers to the c-strings(arrays of characters).
Last edited by scragar (2009-09-26 09:46:03)
Offline
Have you read much about arrays and pointers yet? argv is an array of character pointers. When main is invoked, argv is initialized to the command line arguments and argc is set to the number of arguments. argv[0] is a pointer to the name with which the program was invoked, and argv[argc] is always NULL. Here's a quick sample program, which just prints out the arguments one by one:
#include <stdio.h>
int main(int argc, char *argv[])
{
int i;
for (i = 0; i < argc; i++) {
printf("argv[%d] = \"%s\"\n", i, argv[i]);
}
if(argv[i] == NULL) /* i == argc */
printf("argv[%d] is NULL\n", i);
else
printf("argv[%d] is not NULL.\n", i);
return 0;
}
Actually, if you don't use the arguments, this prototype is also valid:
int main(void)
If you're using gcc with all warnings enabled (which is strongly recommended), the hello world program you mentioned above should have warned you that your main function didn't use its arguments. Use "-W -Wall" to turn on warnings.
And since this post isn't enough of a hodgepodge of random advice already, I'm going to strongly recommend you buy, borrow or check out a copy of The C Programming Language (2nd ed.), by Kernighan and Ritchie. There's a reason they call it the "white bible".
Offline
@techprophet: you switched argc and argv.
whoops, it was late...
Listen to Trent, he looks like a smart guy.
Offline
Have you read much about arrays and pointers yet? argv is an array of character pointers. When main is invoked, argv is initialized to the command line arguments and argc is set to the number of arguments. argv[0] is a pointer to the name with which the program was invoked, and argv[argc] is always NULL. Here's a quick sample program, which just prints out the arguments one by one:
#include <stdio.h> int main(int argc, char *argv[]) { int i; for (i = 0; i < argc; i++) { printf("argv[%d] = \"%s\"\n", i, argv[i]); } if(argv[i] == NULL) /* i == argc */ printf("argv[%d] is NULL\n", i); else printf("argv[%d] is not NULL.\n", i); return 0; }
Actually, if you don't use the arguments, this prototype is also valid:
int main(void)
If you're using gcc with all warnings enabled (which is strongly recommended), the hello world program you mentioned above should have warned you that your main function didn't use its arguments. Use "-W -Wall" to turn on warnings.
And since this post isn't enough of a hodgepodge of random advice already, I'm going to strongly recommend you buy, borrow or check out a copy of The C Programming Language (2nd ed.), by Kernighan and Ritchie. There's a reason they call it the "white bible".
I'll look into it, thanks.
Offline
Don't think you can get away with not freeing your pointers. Sooner or later, it will come back to bite you in the... uh... yeah.
Offline
absolutezero1287, something you should think about is that C is a proccedural language while C++ is an object-oriented language. They require thinking about a problem in two very different ways even though they have a lot in common.
You may want to learn C first because it is procedural, which is what you're used to. This is your first compiled language and as you've already found, you have to learn the process as well.
As for recommendations, http://www2.its.strath.ac.uk/courses/c/ seems to cover all the basics. It's unix-centric and even mentions make.
Good luck
Mike
Offline