Basic usage of the htslib api in C
Entering edit mode
11 months ago
ucbtsm8 ▴ 10

I am thinking about incorporating some parts of htslib into a program I am writing in C in order to read in bcf files to memory. I am aware that there isn't any official documentation of how to use the headers in htslib such as vcf.h. I am not super proficient in C, so I am finding just reading the header files a struggle.

I found somewhere that Heng Li posted this code snippet in order to read the contig size from a bcf file

#include "htslib/vcf.h"

int main(int argc, char *argv[])
    htsFile *fp;
    bcf_hdr_t *hdr;
    bcf_idpair_t *ctg;
    int i;
    if (argc == 1) {
        fprintf(stderr, "Usage: print-ctg <in.vcf>\n");
        return 1;
    fp = vcf_open(argv[1], "r");
    hdr = vcf_hdr_read(fp);
    ctg = hdr->id[BCF_DT_CTG];
    for (i = 0; i < hdr->n[BCF_DT_CTG]; ++i)
        printf("%s\t%d\n", ctg[i].key, ctg[i].val->info[0]);
    return 0;

I'd like to play around with this code and try figure out how the whole thing works. However, I am having trouble compiling it (in linux).

I have saved the above code in a file called test_sam.c within the main htslib directory To compile, I think I need to link it against the vcf.c file also in the htslib directory.

If I try

gcc test_sam.c vcf.c -o test

I get

vcf.c:28:10: fatal error: config.h: No such file or directory
   28 | #include <config.h>
      |          ^~~~~~~~~~
compilation terminated.

I was wondering if someone could point me to how to compile this code in unix. Sorry if it a basic question. Thanks.

htslib C development • 435 views
Entering edit mode
11 months ago


gcc test_sam.c  -o test -L/path/to/htslib/dir -I/path/to/htslib/dir -lhts
  • -I/path/to/htslib/dir where to find the C include files
  • -L/path/to/htslib/dir where to find the C libraries
  • -lhts link with htslib

    htslib must be compiled before.

Furthermore the best way for compiling C is to write a Makefile.


Login before adding your answer.

Traffic: 2692 users visited in the last hour
Help About
Access RSS

Use of this site constitutes acceptance of our User Agreement and Privacy Policy.

Powered by the version 2.3.6