Includes question

5 replies [Last post]
Flacon
Title: NooBot
Joined: 06/13/2012
Posts:
BotPoints: 12
User offline. Last seen 8 years 31 weeks ago.

So I'm testing some basic C code and I'm having trouble with includes...

I have 4 files: main.c, functions.c, functions.h, and constants.h

The main:

#include "functions.h"
#include "constants.h"

int main() {
raiseArm(50);
motor(ARM_PORT, 50);
return 0;
}

functions.c:

#include "constants.h"

void raiseArm(int position) {
clear_motor_position_counter(ARM_PORT);
while(get_motor_position_counter(ARM_PORT) < position) {
printf("Motor position = %d\n", get_motor_position_counter(ARM_PORT));
motor(ARM_PORT, 70);
msleep(100);
}
}

functions.h:

#ifndef _FUNCTIONS_H_
#define _FUNCTIONS_H_

void raiseArm(int position);

#endif

constants.h:

#ifndef _CONSTANTS_H_
#define _CONSTANTS_H_

const int ARM_PORT = 0;

#endif

This fails to compile with the error

main.c: In function 'main':
main.c:5:8: error: 'ARM_PORT' undeclared (first use in this function)
main.c:5:8: note: each undeclared identifier is reported only once for each function it appears in

However, if i try to remedy this by including constants.h in the main.c as well, I get:

functions.c.o:(.rodata+0x4): multiple definition of `ARM_PORT'
main.c.o:(.rodata+0x4): first defined here
collect2: ld returned 1 exit status<

So in one case I don't have the constant defined at all in the main, and in the other, it's defined multiple times... How do I fix this? I'd like an explanation of what's going on too! Thanks!

ruler501
ruler501's picture
Title: NooBot
Joined: 01/29/2012
Posts:
BotPoints: 367
User offline. Last seen 7 years 21 weeks ago.

You shouldn't assign a value to the variable in your header.

http://stackoverflow.com/questions/14894698/why-does-extern-const-int-n-... is an example of how to do this properly.

The following would probably work

have
extern const int ARM_PORT;
in your header
and
const int ARM_PORT = 0;
in one of your *.c files

Flacon
Title: NooBot
Joined: 06/13/2012
Posts:
BotPoints: 12
User offline. Last seen 8 years 31 weeks ago.

Ah that makes sense thanks!

peterstrong
peterstrong's picture
Title: NooBot
Joined: 07/05/2016
Posts:
BotPoints: 12
User offline. Last seen 5 years 5 weeks ago.

mark and study,thx

panistefanin
Title: NooBot
Joined: 05/29/2017
Posts:
BotPoints: 64
User offline. Last seen 4 years 16 weeks ago.

I would like to read about it anymore. Prompt, what literature to study?
sprint corporate

Taylorshaw151
Title: NooBot
Joined: 04/20/2017
Posts:
BotPoints: 28
User offline. Last seen 1 week 4 days ago.

I have been working on a robot hand as my project and this is so far the simplest codes I have found for the moving arms of the robot. I would like to share some codes so that you could help me make it simpler. http://pariscitytourguide.com/private-tours-paris/paris-city-tour/