0

I have problems running the following C written code in CodeBlocks:

#include <stdio.h>
#include <stdlib.h>


#define STRLEN 5

int readln(char s[], int maxlen) {
    char ch;
    int i;
    int chars_remain;
    i = 0;
    chars_remain = 1;
    while (chars_remain) {
        ch = getchar();
        if ((ch == '\n') || (ch == EOF)) {
            chars_remain = 0;
        } else if (i < maxlen - 1) {
            s[i] = ch;
            i++;
        }
    }
    s[i] = '\0';
    return i;
}

int main(int argc, char **argv) {
    char firstname[STRLEN];
    char lastname[STRLEN];
    int len_firstname;
    int len_lastname;
    printf("Enter your first name:");
    len_firstname = readln(firstname, STRLEN);
    printf("Enter your last name:");
    len_lastname = readln(lastname, STRLEN);
    printf("Hello, %s, %s\n", firstname, lastname);
    printf("Length of firstname = %d, lastname = %d", len_firstname, len_lastname);
}

This is the error message:

undefined reference to `WinMain@16' error: ld returned 1 exit status

So I am new to this, but I think it has something to do with my compiler. Any clues on how to fix it are greatly appreciated!

  • Are you trying to create a library or an executable? In the latter case, what do you expect your program to do when run? – sepp2k Jun 12 '17 at 09:35
  • 1
    Codeblocks is an IDE not a compiler. The compiler used is most likely GCC as that's the default one in Codeblocks. – Lundin Jun 12 '17 at 09:36
  • I am trying to create an executable. It is supposed to give a function which stores a character string of length maxlen in s[]. It will ask me to type in characters which are stored in s[]. When I type '\n' , the function is done. When I reach maxlen and still haven't typed in '\n', no further characters typed will be stored. –  Jun 12 '17 at 09:41
  • @Luk You've just described what your function is supposed to do. But what is the program supposed to do? Like where should it get the value of maxlen from for example? And what should it do after calling `readln` (like print the result for example)? Either way, once you've decided what your program should do, you'll need to write a main method that does that. – sepp2k Jun 12 '17 at 09:46
  • you're right, sepp2k ! Thx! - I have edited my question. The program now does what I want it to do. I have adopted the code from a book. I have two questions on how the main program works: How can `firstname` and `lastname` be inputs to readln(), when I do not tell my program to store the printf() output in the variables `firstname` or `lastname` respectively? And the `getchar()` that is being used in the `readln` function, how does it know it is supposed to read the characters of the first input argument? Can you help me with this? –  Jun 12 '17 at 10:23

0 Answers0