Multiply defined linker error using inlined functions

后端 未结 5 616
萌比男神i
萌比男神i 2020-12-20 07:44

The linker is reporting multiply defined errors for an inline function.

I have the following code in a header file:

struct Port_Pin
{
    volatile ui         


        
5条回答
  •  遥遥无期
    2020-12-20 08:22

    In C you cannot define a function with the same name in multiple places whether it is inline or not.

    The best way to handle this is to declare the function in a header (along with the structure definition it depends on, like so:

    /* port_control.h */
    
    struct Port_Pin              
    {              
        volatile uint32_t *     port_addr_set_value;    //!< Writing the pin value here sets the pin to high.              
        volatile uint32_t *     port_addr_clr_value;    //!< Writing the pin value to this port clears the pin to low.              
        volatile uint32_t *     port_addr_read_value;   //!< Address to read pin value.              
        volatile uint32_t *     port_addr_enable;       //!< Writing the pin value here enables the pin (for reading or writing).              
        volatile uint32_t *     port_addr_disable;      //!< Writing the pin value here disables the pin.              
        volatile uint32_t *     port_addr_dir_output;   //!< Writing the pin value here sets the pin as an output.              
        volatile uint32_t *     port_addr_dir_input;    //!< Writing the pin value here sets the pin as an input.              
        unsigned int            pin_bit_position;       //!< Zero based, where position zero is first bit position.              
    };              
    
    /* Declare the function here so other modules know about it. */        
    inline void              
    Write_Port_Pin(const struct Port_Pin *  p_port,              
                   uint8_t                  bit);
    

    Then define the function in a .c source file in one place:

    /* port_control.c */
    
    #include "port_control.h"
    
    inline void                     
    Write_Port_Pin(const struct Port_Pin *  p_port,                     
                   uint8_t                  bit)                     
    {                     
        volatile uint32_t * port_addr = 0;                     
        port_addr = ((bit & 1) == 0) ? p_port->port_addr_clr_value                     
            : p_port->port_addr_set_value;                     
        *port_addr = 1 << p_port->pin_bit_position;                     
        return;                     
    } 
    

    Then #include this header file in all of the .c files that call the function.

提交回复
热议问题