1

Sorry if this is a repeat question, but I couldn't find an answer that worked.

I'm writing a Hello World C program for the first time in a long time. I'm fairly certain the code is right, but it won't compile.

Running MAC OS 10.13.6 and I just downloaded XCode last week. The program compiles into an object file using

cc -c test.c -o test.o

without a problem. However, I can't create an executable using

cc test.o -o test

Here's the code:

#include <stdio.h>
int Main()
{
    printf("Hello World");
    return 0;
}

When I go to create the executable, I get

Undefined symbols for architecture x86_64:
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture x86_64

I'm guessing I need to add some compiler flags but can't figure out which ones.

alk
  • 69,737
  • 10
  • 105
  • 255
SteveTake2
  • 41
  • 3
  • 3
    `int Main()` this is not how you write a main function in C. – tkausl Jan 20 '19 at 15:38
  • 2
    Names in C are case sensitive, and the entry point function needs to be named "main", not "Main". – John Bollinger Jan 20 '19 at 15:38
  • C is case sensitive "Main" is not "main" – Alain Merigot Jan 20 '19 at 15:38
  • And when `main()` takes no parameters it is `int main(void)`. – Swordfish Jan 20 '19 at 16:24
  • Apart from the multiple comments above which tell you how to fix. I would bet that your build tools also told you so. Could you show the verbatim full error message you got? a) The one you got. b) The one you get when you use strict warnings and a nitpicking configuration of build tools. Start with `-Wall`. – Yunnosch Jan 20 '19 at 16:28
  • See it tells you that it is looking for something called "main" not "Main". Even though the "_" might be confusing, this should have made you aware of the capitalisation mistake. Reading error messages really is the best first level of help with anything that does not build. – Yunnosch Jan 20 '19 at 16:30
  • 1
    @alk People tend to confuse beginner mistakes with bad questions. – Yunnosch Jan 20 '19 at 16:34
  • Thanks - pay attention to case, got it – SteveTake2 Jan 20 '19 at 17:57

1 Answers1

5

It sounds like you are just starting out in your journey into c code. This is a great opportunity to learn about c, compiling, and linking.

What you have written can compile just fine into an object file (containing a function called Main()). However, to link into an executable that can run from your OS, you need to define an entry point which is assumed to be a function called main (case sensitive as John mentioned above).

Check out this resource: http://www.ntu.edu.sg/home/ehchua/programming/cpp/gcc_make.html for an explanation of what the gcc compiler gets up to behind the scenes.

You just need to make a couple of small changes to get your code to work as expected:

#include <stdio.h>

int main(void) {
    printf("Hello, world!\n");
    return 0;
}
bolov
  • 72,283
  • 15
  • 145
  • 224