简体   繁体   中英

Can't get ANSI C code to compile with gcc

I got the following code from "The C Programming Language" written by Brian Kernighan and Dennis Ritchie. However, it won't compile with gcc:

    #include <stdio.h>
    #include <string.h>
    #define MAXLINE 1000

    int getline(char *line, int max);

    {
     char line[MAXLINE];
     int found = 0;

     if (argc != 2)
      printf("Usage: find pattern\n");
     else
      while (getline(line, MAXLINE) > 0)
       if (strstr(line, argv[1])  != NULL) {
          printf("%s", line);
          found++;
       }
      return found;
    }

All I get is: error: expected identifier or '(' before '{'.

What am I doing wrong?

As this answer says, you omitted the line that declares the main function.

This line:

int getline(char *line, int max);

is a declaration of the getline function, which must be defined elsewhere. (If you dropped the ; , it could also be the first line of a full definition of getline , but that doesn't seem to be the intent.)

In this case, the intent appears to be for it to be defined in a different source file. You'll need to compile both that source file and this one, and then use the linker to combine them into an executable program.

You may run into another problem, though. Some implementations provide their own non-standard function called getline , and it's not compatible with the way you've declared it. If you're using gcc, you'll need to compile with an option that inhibits that non-standard definition, such as -ansi or -std=c99 . For simplicity, you might consider using a name other than getline ; get_line should be ok.

And of course you'll need to define the getline or get_line function somewhere. (You can put the definition in the same source file if you like, but I suspect the point of this exercise is to build programs from multiple source files.)

Remove ; from

int getline(char *line, int max);  
                                ^
                                |
                             remove this semicolon 

I think you missed this line:

main(int argc, char *argv[])

Arguments in main() ignored when debugging in Visual C++

int getline(char *line, int max);   // <-- Delete that semi-colon
{

删除分号:

int getline(char *line, int max)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM