Abhi12
Abhi12

Reputation: 23

Error in compiling before linking the object files using gcc

I have source files written in C programming using notepad++ and I am running them from command lines and later i need to link them inorder to generate the .exe file.

Here are the following commands I want to use while generating .exe file

gcc logc.c -o logc
gcc mainc.c -o mainc

gcc -o output logc.o mainc.o

But when i run the following command my compiler is returning with the following error status.

gcc logc.c -o logc

(x86)/mingw-w64/i686-8.1.0-win32-dwarf-rt_v6-rev0/mingw32/bin/../lib/gcc/i686-w64-mingw32/8.1.0/../../../../i686-w64-mingw32/lib/../lib/libmingw32.a(lib32_libmingw32_a-crt0_c.o):crt0_c.c:(.text.startup+0x39): undefined reference to `WinMain@16'

when i run the following command to compile my mainc file

C:\Users\user\AppData\Local\Temp\ccskY3nf.o:mainc.c:(.text+0x31): undefined reference to `Log'
collect2.exe: error: ld returned 1 exit status

And here are my mainc.c and logc.c and logc.h files for your reference

logc.c file is here

#include <stdio.h>
#include "logc.h"

void InitLog()
{
    Log("Initializing Log");
}

void Log(const char* message)
{
    printf(" %s",message);

}

mainc.c file is here

#include <stdio.h>
#include <conio.h>
#include <stdbool.h>
#include "logc.h"

    int main()
    {
        int x = 5;
        bool comparisonResult = x == 5;
        if(comparisonResult == 1)
            Log("Hello World"); 
        return 0;
    }

and logc.h file is here

#ifndef _LOG_H
#define _LOG_H

void InitLog();
void Log(const char* message);

#endif

How can i compile individual source files and then link them and generate an executable file.

Thanks in advance.

Upvotes: 2

Views: 245

Answers (2)

dbush
dbush

Reputation: 224082

By default gcc will generate an executable file, not an object file. So when you compile logc.c, it tries to make an executable but it can't find the main function so it fails. Similarly with main.c, it tries to make an executable but can't find Log

You need to add the -c option to create object files:

gcc logc.c -c -o logc.o
gcc mainc.c -c -o mainc.o

Upvotes: 0

Some programmer dude
Some programmer dude

Reputation: 409196

You don't create object files, for that you need the -c argument:

gcc logc.c -c
gcc mainc.c -c

gcc -o output logc.o mainc.o

Upvotes: 2

Related Questions