Learning C++ on a Mac

Discussion in 'Mac Programming' started by James-B, Oct 6, 2009.

  1. macrumors newbie

    Joined:
    Oct 6, 2009
    #1
    Dear All,

    I need to learn C++ (a common problem no doubt) and could really do with some help. I've been browsing through an online tutorial and would like to try writing and running some basic code on my Mac. Could someone give me some pointers as to how I can go about doing this?, i.e. how I can set up an environment (if that's the right word) where I can type C++ and see what it does? (Please also bear in mind that I know next to nothing about computers and how they work and the various terms involved). I have OS 10.4 and, based on what I read somewhere, have downloaded XCode 2.5 on the basis that this will help me. Any and all suggestions greatly appreciated,

    James.
     
  2. macrumors G4

    Joined:
    Jan 5, 2006
    Location:
    Redondo Beach, California
    #2
    You have everything you need. Just start up a terminal session, create a file with your very simple "hello world" program in it and compile withj gcc.

    You will need to buy a beginner book. The Mac is a UNIX computer and the example the assume you are working with a UNIX command line prompt will work.

    But, you will need to know about computers before you can start. You need to understand about files, directories, text editors and so on at the very least.

    You next step is to find a beginner level programming book.
     
  3. macrumors newbie

    Joined:
    Jul 19, 2009
    #3
    Since you are just starting and you want to write and compile code, you can just use your terminal. It's much simpler than using Xcode and having to make a project every single time. You can use vi or nano, they are just text editors.

    Open up a terminal, it's in your utilities folder. Type nano
    You can copy and paste the code below as a start.
    Hit ctrl+x and save it as whatever.cpp.
    Code:
    
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
             int one = 1;
             int two = 2;
             int four = 4;
    
            cout << "The numbers 1, 2, 4 add up to:\t" << one + two + four << "\n";
            return 0;
    }
    
    To compile it, you just type this into your terminal...

    Code:
    g++ whatever.cpp
    and to run it type this

    Code:
    ./a.out
    Hope this helps...
     
  4. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #4
    Thanks for the response Chris. I think I at least know about folders and directories and stuff like that. And I know a little VBA so have at least some exposure to writing code. I'll have a look at doing the first thing you've suggested, namely

    DMC333. Thanks also. I don't get anything when I type nano though. I have something called terminal.app, but when I paste your code in there it does strange things. Have I misunderstood you?
     
  5. macrumors newbie

    Joined:
    Jul 19, 2009
    #5
    You have to type nano in the terminal.app. Nano is a text editor that runs in the terminal.
     
  6. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #6
    I see. Thanks. When I type

    Code:
    g++ whatever.cpp
    though, it says -bash: g++: command not found. Do I need to save the file in a certain place or something?
     
  7. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #7
    You said you downloaded Xcode - did you install it yet?
     
  8. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #8
    Not yet. You think I should do so, yes?
     
  9. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #9
    Yes, you need to install Xcode to compile your code.
     
  10. macrumors 6502a

    electroshock

    Joined:
    Sep 7, 2009
    #10
    In addition to what others has said, you can do it as:

    Code:
    g++ whatever.cpp -o whatever
    ./whatever
    That saves you the step of needing to rename it from a.out for every file you compile. Well, all that after you have Xcode installed (to obtain the compilers). :)
     
  11. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #11
    Magic. Thank you all. That seems to work. Can someone now explain to me what's going on here (or point me in the direction of some useful links that do so)?

    The terminal is some kind of facility where you can type instructions that get some to some part of the computer to be processed? And nano is the part of the terminal that handles c++? Or what?
     
  12. Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #12
    Terminal.app is equivalent to Windows' "Command Prompt" a place where the shell (in this case bash, cmd.exe in windows) can receive and process commands.

    nano is just a text editor, roughly equivalent to notepad.exe, can be replaced with any text editor of your choice.

    g++ is the c++ compiler part of the gcc toolchain this takes the c++ code in the text file and makes it into an executable.

    EDIT: http://www.cplusplus.com/ is a good resource for once you've got your bearings, but probably not quite yet at the stage you're at.

    B
     
  13. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #13
    Right. So the line

    Code:
    g++ whatever.cpp -o whatever
    is saying: Have a look at the file called whatever; see what language it's in based on its extension; and compile it into an executable file? Or something like that?

    If so, how does it know where to look for whatever?
     
  14. macrumors 6502a

    electroshock

    Joined:
    Sep 7, 2009
    #14
    g++ is the GNU C++ compiler.

    So that command is saying:

    The GNU C++ compiler will go and compile a C++ file called whatever.cpp and create the output (executable) file called whatever.

    By default, it will search your current directory -- whatever directory you are in at the time -- for whatever.cpp, and will also put the executable in the current directory. You can tell it to look for files in other places or to put the built executable in other places.

    For example:

    g++ ~/Downloads/foo.cpp -o bar

    Would look for a file called 'foo.cpp' in your Downloads folder in your account, and it would create an executable named 'bar' in your current directory.

    Or:

    g++ coolest.cpp -o /tmp/cool

    That would search your current directory for a file named 'coolest.cpp', compile it, then put the executable named 'cool' in the /tmp directory.
     
  15. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #15
    I see. Great, thanks. Couple of questions then:

    a] Is there a way of "stepping through" C++ a line at a time to see what's happening? (My only exposure to programming has been been VBA where I could do this kind of thing), and

    b] Can I get set up on this forum so I get emailed every time someone posts on certain threads?
     
  16. macrumors 6502

    Joined:
    Apr 24, 2008
    #16
    a] That'd probably be easiest in Xcode. The original "gdb" interface is text-based, but it's easier to use the debugger in Xcode.

    b] Check your "User CP", on the top left of this page. The go to "Edit Options", look for "Messaging & Notification", and set "Default Thread Subscription Mode" to your liking.
     
  17. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #17
    Many thanks. Another question then: Where's the best place to go to find out what commands do what? Suppose, for instance, I want to find out how to calculate the log of n base 3. Do I just google, or are there certain authoritative places to look?
     
  18. Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #18
    The site I linked to earlier is a good resource, but you need to know what libraries to load. See for example:

    http://www.cplusplus.com/reference/clibrary/cmath/log/

    Note that you need to use log identities to switch bases from e, so

    log3 = log(n)/log(3);

    would put the log of n base 3 in a variable called log3.

    B
     
  19. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #19
    So a book arrived this afternoon and I've read through the first couple of chapters. It's set me an exercise of writing a routine that lists all the primes between 1 and 100. Here was my first attempt at it:

    Code:
    #include <iostream>
    using namespace std;
    
    // print out the primes between 1 and 100
    const char n = 100;
    int main ()
    {
      bool b = 1;
      for (char i = 2; i <= n; i++) {
    	for (char ii = 2; ii <= i/2 - 1; ii++) {
          if (i % ii == 0) {b = 0;}
    	}
    	if (b) {cout << (int) i << ", ";} else {b = 1;}
      }
      cout << "\b\b\n";
      return 0;
    }
    I was wondering if anyone could give me any pointers on better ways to do things, better logic to use, ways of laying things out, etc? It seems a bit clumsy to me. Thanks again, James.

    P.S. As you'll no doubt be able to tell, my attempt at deleting the last ", " doesn't work.
     
  20. macrumors regular

    Joined:
    Feb 27, 2008
    #20
    It's not required to put single statement into curly braces - it may help to improve readability though. You can stop looping by ii when you find that i is not prime - 'break;' If you don't know what item is last, put ',' before each item except the first (that is 2 in this case). For general calculations 'int' may be faster than 'char' and you don't need to think about overflow in most cases.
     
  21. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #21
    Many thanks. All good tips. I was actually looking at using the break statement as I got your email. I was experimenting with the following

    Code:
    #include <iostream>
    using namespace std;
    
    // print out the primes between 1 and 100
    const char n = 100;
    int main ()
    {
      for (char i = 2; i <= n; i++) {
    	for (char ii = 2; ii <= i/2 - 1; ii++) {
          if (i % ii == 0) {break;}
    	}
    	if (ii == i/2) {cout << (int) i << ", ";}
      }
      cout << "\b\b\n";
      return 0;
    }
    but can't get it to work. Does the break statement do something to the variables in the loop it breaks? My thinking was that if the loop had completed without breaking, then ii would be i/2. But the line beginning "if (ii == i/2)" seems to be causing problems.
     
  22. macrumors newbie

    Joined:
    Nov 2, 2006
    #22
    Heheh... you need pointers. :D
     
  23. Moderator

    balamw

    Staff Member

    Joined:
    Aug 16, 2005
    Location:
    New England
    #23
    Wirelessly posted (Mozilla/5.0 (iPhone; U; CPU iPhone OS 3_1 like Mac OS X; en-us) AppleWebKit/528.18 (KHTML, like Gecko) Version/4.0 Mobile/7C144 Safari/528.16)

    And not meaning suggestions or tips. ;)
     
  24. thread starter macrumors newbie

    Joined:
    Oct 6, 2009
    #24
    Right. Pointers are a few chapters away, so I'll just keep reading for now. Thanks.
     
  25. macrumors regular

    Joined:
    Feb 27, 2008
    #25
    This is not the way you want to report problems with... well, with anything computer-relaterd. If it doesn't compile ( it doesn't), post exact compiler error text. If it doesn't work as expected (it doesn't as well after compiler error is fixed, it prints 4 as a prime) post expected result and actual result.

    It doesn't compile because ii is visible only within 'for' loop in which header it was declared, it's called scope.
    And 4 is because you don't check '2' as divisor ( 4/2 - 1 == 1)
     

Share This Page