簡體   English   中英

如果至少未使用-O2,則clang Linker失敗

[英]clang Linker fails if at least -O2 wasn't used

我在出於教育目的的簡單C代碼中有一種舉止行為。

如果我用低於-O2的值進行編譯,則在此輸出的鏈接編輯期間會中斷。

$ make
clang -Wall -march=native -pipe -c -g -D_DEBUG_ main.c
clang -Wall -march=native -pipe -c -g -D_DEBUG_ functions.c
clang -Wall -o main main.o functions.o 
Undefined symbols for architecture x86_64:
  "_getbit", referenced from:
      _getValueFromMatrix in functions.o
  "_setbit", referenced from:
      _populateMatrix in functions.o
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)
make: *** [main] Error 1

我不知道這是否有幫助,但是,這是setbit()的實現; 和getbit();

inline void setbit(uint64_t *inteiro, unsigned char pos) {
    *(uint64_t*)inteiro |= (uint64_t)1 << pos;
}

inline bool getbit(uint64_t inteiro, unsigned char pos) {
    return (inteiro & ((uint64_t)1 << pos));
}

編輯:

functions.h

#ifndef __FUNCTIONS_H__
#define __FUNCTIONS_H__

/* Funções para manipulação de bits */

inline void setbit(uint64_t *, unsigned char);

inline void clearbit(uint64_t *, unsigned char);

inline bool getbit(uint64_t, unsigned char);

inline unsigned char getbitChar(uint64_t, unsigned char);

char *uint64_t2bin(uint64_t, char *, int);

#endif

包含在main.c中

#include <stdio.h>
#include <stdlib.h>
#include <stdint.h>
#include <stdbool.h>
#include <string.h>

#include "errors.h"
#include "const.h"
#include "types.h"
#include "functions.h"

如果.h文件中有函數的定義,則僅使用inline是正確的選擇。 它基本上告訴編譯器不應在每個編譯單元(您的.c文件)中為該函數生成代碼。

如果.h文件中沒有這樣的定義(如此處所示),則根本不使用inline ,這毫無意義。

如果您擔心定義inline函數的單元中其他函數的效率,則實際上不需要。 編譯器將內聯任何可以使用的函數,並且在其條件認為值得這樣做的地方。

如果你真想把定義出現在頭文件,使得各單位可以看到的定義, 然后inline 在這種情況下,您必須僅在一個單元中包含函數的“實例化”,以確保代碼恰好發出一次:

extern inline void setbit(uint64_t *, unsigned char);
extern inline void clearbit(uint64_t *, unsigned char);
extern inline bool getbit(uint64_t, unsigned char);
extern inline unsigned char getbitChar(uint64_t, unsigned char);

內聯函數沒有任何外部定義,因此當編譯器無法內聯它們時(在-O0處不會執行),鏈接器將找不到定義,並產生錯誤。 最簡單的解決方法是將inline更改為static inline 非靜態內聯很難使用,引起混亂,並且通常沒有用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM