Search code examples
cmakefilelinker-errorsundefined-symbol

Undefined Symbol for Architecture x86_64 - C


I'm beginning to write a program in C but I have the following error and I can't figure out why:

Undefined symbols for architecture x86_64:
  "_receiveByte", referenced from:
      _main in main_prog.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [q1] Error 1

As far as I understand, I have included everything properly in the appropriate files and in my makefile, yet I still get this error. This is what my code looks like:

main_prog.c

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

#include "physical.h"
#include "main_prog.h"

int main(int argc, char *argv[]) 
{
    PhysicalState * initPhysical();
    const Direction blah = L2R;

    unsigned char new_char; 
    new_char = receiveByte(blah);

    printf("Done.\n");
}

main_prog.h

#ifndef _MAIN_PROG_H
#define _MAIN_PROG_H

// nothing yet

#endif

physical.h

#ifndef _PHYSICAL_H
#define _PHYSICAL_H

#include <pthread.h>

#define MAX_FRAME_SIZE 1024

typedef enum
{
  false,
  true
} boolean;

typedef enum
{
  L2R,
  R2L
} Direction;

struct PHYSICAL_STATE
{
  pthread_cond_t  L2RTxSignal;     
  pthread_cond_t  L2RRxSignal;     
  boolean         L2RReady;        
  pthread_mutex_t L2RLock;       

  pthread_cond_t  R2LTxSignal;     
  pthread_cond_t  R2LRxSignal;     
  boolean         R2LReady;        
  pthread_mutex_t R2LLock;        
};

typedef struct PHYSICAL_STATE PhysicalState;

PhysicalState * initPhysical();

unsigned char receiveByte(const Direction dir);

#endif

and finally my

makefile

PROG = main_prog
HDRS = physical.h main_prog.h
SRCS = main_prog.c 

OBJDIR = object
OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(SRCS)) 

CC = gcc
CFLAGS = -Wall --std=c99 -L.
LIBS = -lm

all : $(OBJDIR) $(PROG)

$(PROG) : $(OBJS)
    $(CC) $(CFLAGS) $^ -o $(PROG) $(LIBS)

object/%.o : %.c $(HDRS)
    $(CC) -c $(CFLAGS) $< -o $@ $(LIBS)

$(OBJDIR) :
    mkdir -p $@/

clean:
    rm -rf object/
    rm -f $(PROG)

There is also a physical.o file located in the same directory as all of these files, whereas the main_prog.o file gets located in object/ as specified by the makefile. I've tried moving the physical.o file around as well as the main_prog.o file around (and changing the makefile to correspond) but I still get this error. Any solution to this error would be greatly appreciated thanks.


Solution

  • Your OBJS makefile variable doesn't include physical.o, so you're not actually linking in that object file. Try listing it as something like

    OBJS = $(patsubst %.c, $(OBJDIR)/%.o, $(SRCS)) physical.o