简体   繁体   English

C从另一个文件嵌入结构的更改值

[英]C embedded change values of struct from another file

Hello I am working on a small roboter project at uni and I have run into following issue.您好,我正在 uni 从事一个小型机器人项目,但遇到了以下问题。 I have a typedef called RoboterData inside of a header file because I want to make use of it across multiple files.我在头文件中有一个名为 RoboterData 的 typedef,因为我想在多个文件中使用它。 Inside of the main file I have a RoboterData data variable which holds important data.在主文件中,我有一个 RoboterData 数据变量,其中包含重要数据。

My goal is to have access from other files to this data having the ability to get and set it from another file.我的目标是从其他文件访问此数据,并能够从另一个文件获取和设置它。 I want to avoid the use of a global variable.我想避免使用全局变量。

Here are the relevant code fragments of my approach:以下是我的方法的相关代码片段:

main.h主文件

typedef struct {
    DriveMode mode;
    short sensor_left;
    short sensor_mid;
    short sensor_right;
    int left_eng_speed;
    int right_eng_speed;
} RoboterData;

main.c主文件

# include "motors.h"

// The Data I want to get and set from other files.
RoboterData data;

// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);

motors.h电机.h

void drive_straight(RoboterData *data);

motors.c马达.c

# include "main.h"

enum {
    ENG_STILL = 0,
    ENG_SLOW = 50,
    ENG_MID = 155,
    ENG_FAST = 200
}

void drive_straight(RoboterData *data) {
    data ->left_eng_speed = ENG_FAST;
    data ->right_eng_speed = ENG_FAST;
    set_duty_cycle(LEFT_ENG, ENG_FAST);
    set_duty_cycle(RIGHT_ENG, ENG_FAST);
}

When I later try to print out the values left_eng_speed and right_eng_speed via serial port it stays at 0. I know C is call by value but since I am passing a ptr to my struct the value I am passing is the adress of the struct and when I dereference it via '->' I should be able to access its original data from my understanding and not a copy because the only thing I copied was the address.当我稍后尝试通过串行端口打印出 left_eng_speed 和 right_eng_speed 值时,它保持为 0。我知道 C 是按值调用的,但是由于我将 ptr 传递给我的结构,因此我传递的值是结构的地址,何时我通过'->'取消引用它我应该能够根据我的理解访问它的原始数据而不是副本,因为我复制的唯一内容是地址。

If someone could explain to me why this is not working and provide a viable alternative, I would be very greatfull.如果有人可以向我解释为什么这不起作用并提供可行的替代方案,我会非常满意。

// Call to a funcion defined in motors.c
drive_straight(RoboterData *data);

This is a function declaration.这是一个函数声明。 It doesn't do anything.它什么也不 You want你要

drive_straight(&data);

to actually call the function.实际调用该函数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM