0

I have 3 directories, src, lib, and include. In include I have header file header3.h. Its code is as follows:

//header3.h
extern void change(int *a);

In lib I have file change4.c, which contains:

//change4.c
#include <stdlib.h>
#include "header3.h"

void change(int *a){
    int y=100;
    *a=y;
}

In src I have file manipulate5.c, which contains:

//manipulate5.c
#include <stdio.h>
#include "header3.h"

int main(void){
     int x=10;
     printf("x is %d\n", x );
     change(&x);
    printf("x is now %d\n", x );
}

I have created object files manipulate5.o and change4.o for files manipulate5.c and change4.c respectively. How do I link the two when manipulate5.o is in src and change4.o is in lib?

I should further clarify; I am supposed to be able to run the executable when in the src directory. Thus, I am not allowed to do the compiling in the root directory.

  • 2
    Manually. What else? – Sourav Ghosh Jun 08 '18 at 16:43
  • 1
    You need to fix `change()` — assigning an integer to a pointer is wrong on several grounds. Use `*a = y;` (and spaces are cheap — use them consistently). – Jonathan Leffler Jun 08 '18 at 16:47
  • Assuming current directory is the one holding `src` and `lib`, then `cc -o program src/manipulate5.o lib/change4.o` — where `cc` is the name of your C compiler, of course. If you've not created the object files, use the names ending `.c`; it won't be much slower on the code shown. – Jonathan Leffler Jun 08 '18 at 16:48
  • Can you please tell me what "Manually" entails? And changing change is not the problem; the computer is telling me that change4.o simply does not exist. –  Jun 08 '18 at 16:50
  • Jonathon Leffler: Thanks for your answer. It works well enough for my purposes. –  Jun 08 '18 at 17:01

1 Answers1

0

Looks like you want to use the linker. I am assuming you are on linux. ld is what you want to use. Something like

ld -o executableName lib/change4.o src/manipulate5.o

This is assuming you are at the top level of your project. You will also have to change both inclusions of the header to

#include "../include/header3.h"
Pillager225
  • 439
  • 1
  • 3
  • 15
  • More rules; I am not allowed to use relative pathings in my include statements. –  Jun 08 '18 at 16:56
  • Then there is no way to do what you want. How does either of those files know where to find the header? You could just put everything into the same directory then. – Pillager225 Jun 08 '18 at 16:56
  • I have been doing -I ../include in my compile statements, and it seems work. `include` contains my header. –  Jun 08 '18 at 16:58
  • So you are using gcc to compile? Then you don't need to use ld. gcc links for you after it compiles. All you need to do is gcc all the o files together. `gcc lib/change4.o src/manipulate5.o` – Pillager225 Jun 08 '18 at 17:03