Skip to content

Instantly share code, notes, and snippets.

@quarnster
Created September 9, 2012 18:48
Show Gist options
  • Save quarnster/3686396 to your computer and use it in GitHub Desktop.
Save quarnster/3686396 to your computer and use it in GitHub Desktop.
Minimal libclang test code
// clang test.cpp -lclang -o ./test && ./test
// gcc test.cpp -lclang -o ./test && ./test
#include "clang-c/Index.h"
#include <stdio.h>
int main(int argc, char** argv)
{
CXIndex idx = clang_createIndex(1, 0);
const char *clangargs[] =
{
"-I.",
"-x", "c++"
};
// Parse the source file into a translation unit
CXTranslationUnit tu = clang_parseTranslationUnit(idx,
"test.cpp",
clangargs, sizeof(clangargs)/sizeof(char*),
NULL, 0,
CXTranslationUnit_PrecompiledPreamble);
if (!tu)
{
printf("Couldn't parse tu\n");
clang_disposeIndex(idx);
return 1;
}
// Perform a code completion operation
CXCodeCompleteResults* results = clang_codeCompleteAt(tu, "test.cpp", 10, 1, NULL, 0, clang_defaultCodeCompleteOptions());
if (results)
{
clang_sortCodeCompletionResults(results->Results, results->NumResults);
for (int i = 0; i < results->NumResults; i++)
{
CXCompletionString &compString = results->Results[i].CompletionString;
for (int j = 0; j < clang_getNumCompletionChunks(compString); j++)
{
CXString s = clang_getCompletionChunkText(compString, j);
printf("%s ", clang_getCString(s));
clang_disposeString(s);
}
printf("\n");
}
clang_disposeCodeCompleteResults(results);
}
else
{
printf("Failed to perform completion operation\n");
}
// Show any diagnostic information if available
for (unsigned int i = 0; i < clang_getNumDiagnostics(tu); i++)
{
CXDiagnostic diag = clang_getDiagnostic(tu, i);
CXString s = clang_getDiagnosticSpelling(diag);
printf("%s\n", clang_getCString(s));
clang_disposeString(s);
clang_disposeDiagnostic(diag);
}
printf("Total diagnostics available: %d\n", clang_getNumDiagnostics(tu));
clang_disposeTranslationUnit(tu);
clang_disposeIndex(idx);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment