cgcc

Error: "expected ‘)’ before string constant"


I'm trying to run a C program in Ubuntu (using the gcc compiler), and for some reason it's not allowing me to use the strcpy function. On the second line of code below:

char test[10];
strcpy(test, "Hello!");

char c[2] = "A";
strcpy(test, c);

I get the following errors:

testChTh.c:56:14: error: expected ‘)’ before string constant
 strcpy(test, "Hello!");
              ^
testChTh.c:59:1: warning: data definition has no type or storage class
 strcpy(test, c);
 ^
testChTh.c:59:1: warning: type defaults to ‘int’ in declaration of ‘strcpy’ [-Wimplicit-int]
testChTh.c:59:1: warning: parameter names (without types) in function declaration
testChTh.c:59:1: error: conflicting types for ‘strcpy’
In file included from testChTh.c:3:0:
/usr/include/string.h:125:14: note: previous declaration of ‘strcpy’ was here
 extern char *strcpy (char *__restrict __dest, const char *__restrict __src)

I've included the following headers:

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

I've tried using strcpy in a new file with nothing extra, with the same error. I've also tried using:

memset(test, '\0', sizeof(test));

immediately before using strcpy, to no avail.

I've checked all of my opening parenthesis, and they all have a corresponding closing ). Also, when I comment out the strcpy line, the error goes away.

Any insight is much appreciated.


Solution

  • char test[10];
    strcpy(test, "Hello!");
    
    char c[2] = "A";
    strcpy(test, c);
    

    If I understand correctly, you have those lines lines at file scope. The line

    strcpy(test, "Hello!");
    

    is a statement, and statements are legal only inside a function body. Because the compiler wasn't expecting a statement at that point, it tried to interpret that line as a declaration.

    The following, based on your code, is legal (though it doesn't do anything useful):

    #include <string.h>
    int main(void) {
        char test[10];
        strcpy(test, "Hello!");
    
        char c[2] = "A";
        strcpy(test, c);
    }