You are not logged in.

#1 2017-01-24 13:07:55

mikaelbrun
Member
From: Tistedal/ Norway
Registered: 2016-01-01
Posts: 43

[SOLVED]C++ linking problems (need some explaining)

I am trying to include pciaccess.h to my C++ program, but I'm failing to understand the linking stuff. I have search the web, and read alot about this topic, but still can't make it work.
I'm not that advanced in programming, but know the basics.

I have borrowed some parts from radeontop (that is written in C), and is now trying to use this in C++, since I'm more comfortable with this.
The source file is:

/* Test file for system monitoring */ 

#include <stdio.h>
//#include <pciaccess.h>


unsigned int initPci(unsigned char bus, const unsigned char forcemem);

/* THIS DIDN'T WORK VERY WELL
extern "C" {
  int pci_system_init(void);
  const struct pci_id_match *match;
  struct pci_device_iterator *iter;
  struct pci_device *dev;
  int pci_device_probe(struct pci_device *dev);
  struct pci_device *pci_device_next(struct pci_device_iterator *iter);
  void pci_iterator_destroy(struct pci_device_iterator *iter);
}
*/

// NEITHER DID THIS
extern "C" {
  #include <pciaccess.h>
}

int main() {
  unsigned char bus = 0, forcemem = 0;

  const unsigned int pciaddr = initPci(bus, forcemem);
    printf("%d", pciaddr); 

  return 0;
}


// Initialize pci
unsigned int initPci(unsigned char bus, const unsigned char forcemem) {
  int ret = pci_system_init();
  if (ret)
    printf("Failed to init pciaccess"); 

  // Searching criterias??
  struct pci_id_match match;

  match.vendor_id = 0x1002; // 0x1002 is Radeon or AMD
  match.device_id = PCI_MATCH_ANY;
  match.subvendor_id = PCI_MATCH_ANY;
  match.subdevice_id = PCI_MATCH_ANY;
  match.device_class = 0;
  match.device_class_mask = 0;
  match.match_data = 0;

  // Preparing the search loop
  struct pci_device_iterator *iter = pci_id_match_iterator_create(&match);
  struct pci_device *dev = NULL;
  char busid[32];

  // Searching for pci_devices 
  while ((dev = pci_device_next(iter))) {
    pci_device_probe(dev);
    if ((dev->device_class & 0x00ffff00) != 0x0030000 && (dev->device_class & 0x00ffff00) != 0x00038000) {
      continue;
    } // if
    
    snprintf(busid, sizeof(busid), "pci:%04x:%02x:%02x.%u", dev->domain, dev->bus, dev->dev, dev->func); // Prints domain, bus, dev and func to busid

    if (!bus || bus == dev->bus) {
      break;
    } // if
    
  } // while

  // Ending the search loop
  pci_iterator_destroy(iter);

  // Checking if any radeon cards was found
  if (!dev) {
    printf("Can't find Radeon cards"); 
  } // if

  const unsigned int device_id = dev->device_id;

  
  return device_id;
}

The pciaccess.h is found in the /usr/include/ folder:

/*
 * (C) Copyright IBM Corporation 2006
 * Copyright 2009 Red Hat, Inc.
 * All Rights Reserved.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * on the rights to use, copy, modify, merge, publish, distribute, sub
 * license, and/or sell copies of the Software, and to permit persons to whom
 * the Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice (including the next
 * paragraph) shall be included in all copies or substantial portions of the
 * Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NON-INFRINGEMENT.  IN NO EVENT SHALL
 * IBM AND/OR THEIR SUPPLIERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
/*
 * Copyright (c) 2007 Paulo R. Zanoni, Tiago Vignatti
 *
 * Permission is hereby granted, free of charge, to any person
 * obtaining a copy of this software and associated documentation
 * files (the "Software"), to deal in the Software without
 * restriction, including without limitation the rights to use,
 * copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following
 * conditions:
 *
 * The above copyright notice and this permission notice shall be
 * included in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
 * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
 * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
 * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
 * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
 * OTHER DEALINGS IN THE SOFTWARE.
 *
 */

/**
 * \file pciaccess.h
 *
 * \author Ian Romanick <idr@us.ibm.com>
 */

#ifndef PCIACCESS_H
#define PCIACCESS_H

#include <inttypes.h>

#if (__GNUC__ >= 3) || (__SUNPRO_C >= 0x5130)
#define __deprecated __attribute__((deprecated))
#else
#define __deprecated
#endif

typedef uint64_t pciaddr_t;

struct pci_device;
struct pci_device_iterator;
struct pci_id_match;
struct pci_slot_match;

#ifdef __cplusplus
extern "C" {
#endif

int pci_device_has_kernel_driver(struct pci_device *dev);

int pci_device_is_boot_vga(struct pci_device *dev);

int pci_device_read_rom(struct pci_device *dev, void *buffer);

int  __deprecated pci_device_map_region(struct pci_device *dev,
    unsigned region, int write_enable);

int __deprecated pci_device_unmap_region(struct pci_device *dev,
    unsigned region);

int pci_device_map_range(struct pci_device *dev, pciaddr_t base,
    pciaddr_t size, unsigned map_flags, void **addr);

int pci_device_unmap_range(struct pci_device *dev, void *memory,
    pciaddr_t size);

int __deprecated pci_device_map_memory_range(struct pci_device *dev,
    pciaddr_t base, pciaddr_t size, int write_enable, void **addr);

int __deprecated pci_device_unmap_memory_range(struct pci_device *dev,
    void *memory, pciaddr_t size);

int pci_device_probe(struct pci_device *dev);

const struct pci_agp_info *pci_device_get_agp_info(struct pci_device *dev);

const struct pci_bridge_info *pci_device_get_bridge_info(
    struct pci_device *dev);

const struct pci_pcmcia_bridge_info *pci_device_get_pcmcia_bridge_info(
    struct pci_device *dev);

int pci_device_get_bridge_buses(struct pci_device *dev, int *primary_bus,
    int *secondary_bus, int *subordinate_bus);

int pci_system_init(void);

void pci_system_init_dev_mem(int fd);

void pci_system_cleanup(void);

struct pci_device_iterator *pci_slot_match_iterator_create(
    const struct pci_slot_match *match);

struct pci_device_iterator *pci_id_match_iterator_create(
    const struct pci_id_match *match);

void pci_iterator_destroy(struct pci_device_iterator *iter);

struct pci_device *pci_device_next(struct pci_device_iterator *iter);

struct pci_device *pci_device_find_by_slot(uint32_t domain, uint32_t bus,
    uint32_t dev, uint32_t func);

struct pci_device *pci_device_get_parent_bridge(struct pci_device *dev);

void pci_get_strings(const struct pci_id_match *m,
    const char **device_name, const char **vendor_name,
    const char **subdevice_name, const char **subvendor_name);
const char *pci_device_get_device_name(const struct pci_device *dev);
const char *pci_device_get_subdevice_name(const struct pci_device *dev);
const char *pci_device_get_vendor_name(const struct pci_device *dev);
const char *pci_device_get_subvendor_name(const struct pci_device *dev);

void pci_device_enable(struct pci_device *dev);

int pci_device_cfg_read    (struct pci_device *dev, void *data,
    pciaddr_t offset, pciaddr_t size, pciaddr_t *bytes_read);
int pci_device_cfg_read_u8 (struct pci_device *dev, uint8_t  *data,
    pciaddr_t offset);
int pci_device_cfg_read_u16(struct pci_device *dev, uint16_t *data,
    pciaddr_t offset);
int pci_device_cfg_read_u32(struct pci_device *dev, uint32_t *data,
    pciaddr_t offset);

int pci_device_cfg_write    (struct pci_device *dev, const void *data,
    pciaddr_t offset, pciaddr_t size, pciaddr_t *bytes_written);
int pci_device_cfg_write_u8 (struct pci_device *dev, uint8_t  data,
    pciaddr_t offset);
int pci_device_cfg_write_u16(struct pci_device *dev, uint16_t data,
    pciaddr_t offset);
int pci_device_cfg_write_u32(struct pci_device *dev, uint32_t data,
    pciaddr_t offset);
int pci_device_cfg_write_bits(struct pci_device *dev, uint32_t mask,
    uint32_t data, pciaddr_t offset);

#ifdef __cplusplus
}
#endif

/**
 * \name Mapping flags passed to \c pci_device_map_range
 */
/*@{*/
#define PCI_DEV_MAP_FLAG_WRITABLE       (1U<<0)
#define PCI_DEV_MAP_FLAG_WRITE_COMBINE  (1U<<1)
#define PCI_DEV_MAP_FLAG_CACHABLE       (1U<<2)
/*@}*/


#define PCI_MATCH_ANY  (~0U)

/**
 * Compare two PCI ID values (either vendor or device).  This is used
 * internally to compare the fields of \c pci_id_match to the fields of
 * \c pci_device.
 */
#define PCI_ID_COMPARE(a, b) \
    (((a) == PCI_MATCH_ANY) || ((a) == (b)))

/**
 */
struct pci_id_match {
    /**
     * \name Device / vendor matching controls
     *
     * Control the search based on the device, vendor, subdevice, or subvendor
     * IDs.  Setting any of these fields to \c PCI_MATCH_ANY will cause the
     * field to not be used in the comparison.
     */
    /*@{*/
    uint32_t    vendor_id;
    uint32_t    device_id;
    uint32_t    subvendor_id;
    uint32_t    subdevice_id;
    /*@}*/


    /**
     * \name Device class matching controls
     *
     */
    /*@{*/
    uint32_t    device_class;
    uint32_t    device_class_mask;
    /*@}*/

    intptr_t    match_data;
};


/**
 */
struct pci_slot_match {
    /**
     * \name Device slot matching controls
     *
     * Control the search based on the domain, bus, slot, and function of
     * the device.  Setting any of these fields to \c PCI_MATCH_ANY will cause
     * the field to not be used in the comparison.
     */
    /*@{*/
    uint32_t    domain;
    uint32_t    bus;
    uint32_t    dev;
    uint32_t    func;
    /*@}*/

    intptr_t    match_data;
};

/**
 * BAR descriptor for a PCI device.
 */
struct pci_mem_region {
    /**
     * When the region is mapped, this is the pointer to the memory.
     *
     * This field is \b only set when the deprecated \c pci_device_map_region
     * interface is used.  Use \c pci_device_map_range instead.
     *
     * \deprecated
     */
    void *memory;


    /**
     * Base physical address of the region within its bus / domain.
     *
     * \warning
     * This address is really only useful to other devices in the same
     * domain.  It's probably \b not the address applications will ever
     * use.
     *
     * \warning
     * Most (all?) platform back-ends leave this field unset.
     */
    pciaddr_t bus_addr;


    /**
     * Base physical address of the region from the CPU's point of view.
     *
     * This address is typically passed to \c pci_device_map_range to create
     * a mapping of the region to the CPU's virtual address space.
     */
    pciaddr_t base_addr;


    /**
     * Size, in bytes, of the region.
     */
    pciaddr_t size;


    /**
     * Is the region I/O ports or memory?
     */
    unsigned is_IO:1;

    /**
     * Is the memory region prefetchable?
     *
     * \note
     * This can only be set if \c is_IO is not set.
     */
    unsigned is_prefetchable:1;


    /**
     * Is the memory at a 64-bit address?
     *
     * \note
     * This can only be set if \c is_IO is not set.
     */
    unsigned is_64:1;
};


/**
 * PCI device.
 *
 * Contains all of the information about a particular PCI device.
 */
struct pci_device {
    /**
     * \name Device bus identification.
     *
     * Complete bus identification, including domain, of the device.  On
     * platforms that do not support PCI domains (e.g., 32-bit x86 hardware),
     * the domain will always be zero.
     */
    /*@{*/
    uint16_t    domain;
    uint8_t     bus;
    uint8_t     dev;
    uint8_t     func;
    /*@}*/


    /**
     * \name Vendor / device ID
     *
     * The vendor ID, device ID, and sub-IDs for the device.
     */
    /*@{*/
    uint16_t    vendor_id;
    uint16_t    device_id;
    uint16_t    subvendor_id;
    uint16_t    subdevice_id;
    /*@}*/

    /**
     * Device's class, subclass, and programming interface packed into a
     * single 32-bit value.  The class is at bits [23:16], subclass is at
     * bits [15:8], and programming interface is at [7:0].
     */
    uint32_t    device_class;


    /**
     * Device revision number, as read from the configuration header.
     */
    uint8_t     revision;


    /**
     * BAR descriptors for the device.
     */
    struct pci_mem_region regions[6];


    /**
     * Size, in bytes, of the device's expansion ROM.
     */
    pciaddr_t   rom_size;


    /**
     * IRQ associated with the device.  If there is no IRQ, this value will
     * be -1.
     */
    int irq;


    /**
     * Storage for user data.  Users of the library can store arbitrary
     * data in this pointer.  The library will not use it for any purpose.
     * It is the user's responsability to free this memory before destroying
     * the \c pci_device structure.
     */
    intptr_t user_data;

    /**
      * Used by the VGA arbiter. Type of resource decoded by the device and
      * the file descriptor (/dev/vga_arbiter). */
    int vgaarb_rsrc;
};


/**
 * Description of the AGP capability of the device.
 *
 * \sa pci_device_get_agp_info
 */
struct pci_agp_info {
    /**
     * Offset of the AGP registers in the devices configuration register
     * space.  This is generally used so that the offset of the AGP command
     * register can be determined.
     */
    unsigned    config_offset;


    /**
     * \name AGP major / minor version.
     */
    /*@{*/
    uint8_t	major_version;
    uint8_t     minor_version;
    /*@}*/

    /**
     * Logical OR of the supported AGP rates.  For example, a value of 0x07
     * means that the device can support 1x, 2x, and 4x.  A value of 0x0c
     * means that the device can support 8x and 4x.
     */
    uint8_t    rates;

    unsigned int    fast_writes:1;  /**< Are fast-writes supported? */
    unsigned int    addr64:1;
    unsigned int    htrans:1;
    unsigned int    gart64:1;
    unsigned int    coherent:1;
    unsigned int    sideband:1;     /**< Is side-band addressing supported? */
    unsigned int    isochronus:1;

    uint8_t    async_req_size;
    uint8_t    calibration_cycle_timing;
    uint8_t    max_requests;
};

/**
 * Description of a PCI-to-PCI bridge device.
 *
 * \sa pci_device_get_bridge_info
 */
struct pci_bridge_info {
    uint8_t    primary_bus;
    uint8_t    secondary_bus;
    uint8_t    subordinate_bus;
    uint8_t    secondary_latency_timer;

    uint8_t     io_type;
    uint8_t     mem_type;
    uint8_t     prefetch_mem_type;

    uint16_t    secondary_status;
    uint16_t    bridge_control;

    uint32_t    io_base;
    uint32_t    io_limit;

    uint32_t    mem_base;
    uint32_t    mem_limit;

    uint64_t    prefetch_mem_base;
    uint64_t    prefetch_mem_limit;
};

/**
 * Description of a PCI-to-PCMCIA bridge device.
 *
 * \sa pci_device_get_pcmcia_bridge_info
 */
struct pci_pcmcia_bridge_info {
    uint8_t    primary_bus;
    uint8_t    card_bus;
    uint8_t    subordinate_bus;
    uint8_t    cardbus_latency_timer;

    uint16_t    secondary_status;
    uint16_t    bridge_control;

    struct {
	uint32_t    base;
	uint32_t    limit;
    } io[2];

    struct {
	uint32_t    base;
	uint32_t    limit;
    } mem[2];

};


/**
 * VGA Arbiter definitions, functions and related.
 */

/* Legacy VGA regions */
#define VGA_ARB_RSRC_NONE       0x00
#define VGA_ARB_RSRC_LEGACY_IO  0x01
#define VGA_ARB_RSRC_LEGACY_MEM 0x02
/* Non-legacy access */
#define VGA_ARB_RSRC_NORMAL_IO  0x04
#define VGA_ARB_RSRC_NORMAL_MEM 0x08

int  pci_device_vgaarb_init         (void);
void pci_device_vgaarb_fini         (void);
int  pci_device_vgaarb_set_target   (struct pci_device *dev);
/* use the targetted device */
int  pci_device_vgaarb_decodes      (int new_vga_rsrc);
int  pci_device_vgaarb_lock         (void);
int  pci_device_vgaarb_trylock      (void);
int  pci_device_vgaarb_unlock       (void);
/* return the current device count + resource decodes for the device */
int pci_device_vgaarb_get_info	    (struct pci_device *dev, int *vga_count, int *rsrc_decodes);

/*
 * I/O space access.
 */

struct pci_io_handle;

struct pci_io_handle *pci_device_open_io(struct pci_device *dev, pciaddr_t base,
					 pciaddr_t size);
struct pci_io_handle *pci_legacy_open_io(struct pci_device *dev, pciaddr_t base,
					 pciaddr_t size);
void pci_device_close_io(struct pci_device *dev, struct pci_io_handle *handle);
uint32_t pci_io_read32(struct pci_io_handle *handle, uint32_t reg);
uint16_t pci_io_read16(struct pci_io_handle *handle, uint32_t reg);
uint8_t pci_io_read8(struct pci_io_handle *handle, uint32_t reg);
void pci_io_write32(struct pci_io_handle *handle, uint32_t reg, uint32_t data);
void pci_io_write16(struct pci_io_handle *handle, uint32_t reg, uint16_t data);
void pci_io_write8(struct pci_io_handle *handle, uint32_t reg, uint8_t data);

/*
 * Legacy memory access
 */

int pci_device_map_legacy(struct pci_device *dev, pciaddr_t base,
			  pciaddr_t size, unsigned map_flags, void **addr);
int pci_device_unmap_legacy(struct pci_device *dev, void *addr, pciaddr_t size);

#endif /* PCIACCESS_H */

The output when I try to compile is:

/tmp/cclvkePR.o: In function `initPci(unsigned char, unsigned char)':
test.cpp:(.text+0x52): undefined reference to `pci_system_init'
test.cpp:(.text+0xa8): undefined reference to `pci_id_match_iterator_create'
test.cpp:(.text+0xc0): undefined reference to `pci_device_next'
test.cpp:(.text+0xe0): undefined reference to `pci_device_probe'
test.cpp:(.text+0x187): undefined reference to `pci_iterator_destroy'
collect2: error: ld returned 1 exit status

This is what I have tried:

g++ -lm test.cpp -o test
g++ test.cpp /usr/include/pciaccess.h -o test
g++ test.cpp -o test

The same result on every try.

So, I guess I really don't understand how to compile this hmm

Last edited by mikaelbrun (2017-01-24 14:08:15)

Offline

#2 2017-01-24 13:17:29

Trilby
Inspector Parrot
Registered: 2011-11-29
Posts: 29,444
Website

Re: [SOLVED]C++ linking problems (need some explaining)

You need to link to libpciaccess.

Technically compiling and linking are two separate stages and can be done as separate commands - cc to compile and ld to link.  But for most smallish projects, gcc will do all that for you with one command line.  But it does need to know what to link to.

You use some math functions, so you need the math library which you properly include with the `-lm` linker flag.  The math library is actually a bit of an exception as linker flags are generally of the form "-l" followed by the name of the library: if the math library followed the convention the flag for it would be "-lmath".  So to link to libpciaccess you most likely need -lpciaccess.  And you could try this flag - it will probably be sufficient.

However, there is an even easier way.  As many libraries also have their own library dependencies and sometimes have include paths other than /usr/include keeping track of the needed compile and linker flags can be challening.  This is what the pkg-config tool helps with.  Almost any library will come with a .pc file which is for package-config: libpciaacess has one of these.  You can get some information with the following commands:

pkg-config --cflags libpciaccess
pkg-config --libs libpciaccess

In this case, the first doesn't return anything, and the second returns exactly what I expected "-lpciaccess".

So short version, for this instance, just add "-lpciaccess" to the command line.

For future reference, you can use pkg-config as a subshell on a compiler command line:

gcc -lm test.cpp -o test $(pkg-config --cflags --libs pciaccess)

This is generally aided by Makefiles as seen in one of my projects here.  Take a look at lines 15 and 16.  These do a lot of the hard work for me.  I just fill a variabls I called "DEPS" with all the library dependencies (x11, cairo, poppler-glib, and xrandr in this case).  Then the code on lines 15 and 16 calls pkg-config to figure what all the various compiler and linker flags are that I'll need to link to these libraries.  In bigger projects this becomes more and more helpful - just take a look at the output of these commands:

pkg-config --cflags x11 cairo poppler-glib xrandr
pkg-config --libs x11 cairo poppler-glib xrandr

I'd hate to have to remember and type all of that output of those commands myself every time I wanted to recompile my program.

EDIT: I just looked at your code too.  Get rid of all that "extern C" stuff.  That's what the header file does for you.  Just include pciaccess.h (the line you have commented out).  You should do some googling for "dynamic linking" and "shared libraries".  You can look for C resources not jut C++.  In fact I don't see any C++ in your code - it all looks like C code except for the C++ style comments which are now perfectly valid in C as well.

EDIT 2: I just tried your code and it compiled fine (as C code).  But you will get segfaults under many conditions.  At the end of your initPci function you check whether `dev` is null and print an error message if it is.  But then you unconditionally dereference `dev` to get it's member device_id.  This will segfault on systems without Radeon cards (like mine).  I'd put a return under the error message there:

if (!dev) {
   printf("Can't find Radeon cards");
   return -1;
}

That way the subsequent code doesn't run and cause the fault by dereferencing the null pointer.


"UNIX is simple and coherent..." - Dennis Ritchie, "GNU's Not UNIX" -  Richard Stallman

Offline

#3 2017-01-24 14:07:55

mikaelbrun
Member
From: Tistedal/ Norway
Registered: 2016-01-01
Posts: 43

Re: [SOLVED]C++ linking problems (need some explaining)

It's easy when you know what you're doing big_smile !

I thought that making it compatible with my own system first, and then expand as I'm learning.
Thank you for good explaining and help!

PROBLEM SOLVED!
PS! Why can't people write this simple when they write tutorials??

Offline

Board footer

Powered by FluxBB