So I have a simple code that is supposed to run omxplayer in background on my Raspberry Pi :

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

int main()
{
    int pid;
    pid=fork();
    if(pid==0)
    {
            //printf("I am the child\n");
            execlp("/usr/bin/omxplayer", " ", "/home/pi/projects/my_project/aud$
            _exit(0);
    }
    else
    {
            //printf("I am the parent\n");
            wait();
    }

    system("killall omxplayer.bin");
    return 0;
}

But this code doesn't want to be compiled when I try to compile it using gcc play.cpp -o play it gives me these errors :

play.cpp:5:1: error: ‘pid’ does not name a type
 pid=fork();
 ^
play.cpp:6:1: error: expected unqualified-id before ‘if’
 if(pid==0)
 ^
play.cpp:12:1: error: expected unqualified-id before ‘else’
 else
 ^
play.cpp:18:7: error: expected constructor, destructor, or type conversion before ‘(’ token
 system("killall omxplayer.bin");

It's been along time I haven't been on a Raspberry compiler or on c coding so I'm a bit rusted and I may have forgot something stupid but I can't find what.. I fyou can help me thanks in advance !

3  
You likely forgot that code that runs should be in functions? You can't just write such top level ifs into C++ (or looks more like C) code. – Öö Tiib 1 hour ago
1  
For sure! You placed statements outside a function body. It is completely misunderstood by compiler. Put it into int main() { and return 0; }. If you didn't realize this, you urgently have to read a C++ book (or at least a tutorial). – Scheff 1 hour ago

1 Answer 1

Have you tried encapsulating it in a main() method?

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

int main(int argc, char **argv)
{
    int pid;
    pid=fork();
    if(pid==0)
    {
            //printf("I am the child\n");
            execlp("/usr/bin/omxplayer", " ", "/home/pi/projects/my_project/audio/my_file.wav", NULL);
            _exit(0);
    }
    else
    {
            //printf("I am the parent\n");
            wait();
    }

    system("killall omxplayer.bin");
    return 0;
}
    
Yes I did, sorry I just put the rough code here. But actually I found out that my Raspberry needed an installation of c++ libs and I forgot the unistd lib which contains fork..Thank you sorry for the loss of time – JackA 1 hour ago